Skip to content

Commit

Permalink
Speed up Array#split
Browse files Browse the repository at this point in the history
Benchmark:
          user     system      total        real
old   0.510000   0.000000   0.510000 (  0.506749)
new   0.330000   0.000000   0.330000 (  0.336187)
  • Loading branch information
amatsuda committed Jul 10, 2013
1 parent 4536170 commit f660abc
Showing 1 changed file with 20 additions and 6 deletions.
26 changes: 20 additions & 6 deletions activesupport/lib/active_support/core_ext/array/grouping.rb
Original file line number Diff line number Diff line change
Expand Up @@ -86,13 +86,27 @@ def in_groups(number, fill_with = nil)
# [1, 2, 3, 4, 5].split(3) # => [[1, 2], [4, 5]]
# (1..10).to_a.split { |i| i % 3 == 0 } # => [[1, 2], [4, 5], [7, 8], [10]]
def split(value = nil, &block)
inject([[]]) do |results, element|
if block && block.call(element) || value == element
results << []
else
results.last << element
end
if block
inject([[]]) do |results, element|
if block.call(element)
results << []
else
results.last << element
end

results
end
else
results, arr = [[]], self
until arr.empty?
if (idx = index(value))
results.last.concat(arr.shift(idx))
arr.shift
results << []
else
results.last.concat(arr.shift(arr.size))
end
end
results
end
end
Expand Down

0 comments on commit f660abc

Please sign in to comment.