提交 9262e493 编写于 作者: L lvl0nax

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
上级 fb898e98
...@@ -89,24 +89,19 @@ def in_groups(number, fill_with = nil) ...@@ -89,24 +89,19 @@ def in_groups(number, fill_with = nil)
# [1, 2, 3, 4, 5].split(3) # => [[1, 2], [4, 5]] # [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]] # (1..10).to_a.split { |i| i % 3 == 0 } # => [[1, 2], [4, 5], [7, 8], [10]]
def split(value = nil) def split(value = nil)
arr = self.dup
result = []
if block_given? if block_given?
inject([[]]) do |results, element| while (idx = arr.index { |i| yield i })
if yield(element) result << arr.shift(idx)
results << [] arr.shift
else
results.last << element
end
results
end end
else else
arr = self.dup
result = []
while (idx = arr.index(value)) while (idx = arr.index(value))
result << arr.shift(idx) result << arr.shift(idx)
arr.shift arr.shift
end end
result << arr
end end
result << arr
end end
end end
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册