mirror of
https://github.com/rails/rails.git
synced 2022-11-09 12:12:34 -05:00
Array#split refactoring for case with block
Calculating ------------------------------------- before 26.319k i/100ms after 29.414k i/100ms ------------------------------------------------- before 350.623k (± 1.6%) i/s - 1.763M after 416.227k (± 1.4%) i/s - 2.088M Comparison: after: 416226.8 i/s before: 350622.8 i/s - 1.19x slower
This commit is contained in:
parent
fb898e986f
commit
9262e493d5
1 changed files with 6 additions and 11 deletions
|
@ -89,24 +89,19 @@ class Array
|
|||
# [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)
|
||||
arr = self.dup
|
||||
result = []
|
||||
if block_given?
|
||||
inject([[]]) do |results, element|
|
||||
if yield(element)
|
||||
results << []
|
||||
else
|
||||
results.last << element
|
||||
end
|
||||
|
||||
results
|
||||
while (idx = arr.index { |i| yield i })
|
||||
result << arr.shift(idx)
|
||||
arr.shift
|
||||
end
|
||||
else
|
||||
arr = self.dup
|
||||
result = []
|
||||
while (idx = arr.index(value))
|
||||
result << arr.shift(idx)
|
||||
arr.shift
|
||||
end
|
||||
result << arr
|
||||
end
|
||||
result << arr
|
||||
end
|
||||
end
|
||||
|
|
Loading…
Reference in a new issue