Skip to content

Instantly share code, notes, and snippets.

@fbacall
Last active June 17, 2023 23:27
Show Gist options
  • Save fbacall/85994673ec98ccdf68cdf7e4b1288d10 to your computer and use it in GitHub Desktop.
Save fbacall/85994673ec98ccdf68cdf7e4b1288d10 to your computer and use it in GitHub Desktop.
Add alternative stack version
# Allow iteration on a flattened Enumerable.
# e.g. [1,[2,3],[[4]]].flat.map { |x| x * 2 }
#
module Enumerable
def stack_flat_wip(&block)
return to_enum(__method__) unless block_given?
idx = [0]
curr = self
while idx.any? && curr
puts idx.inspect
puts curr.inspect
puts '---'
if idx.last >= curr.length
idx.pop
return if idx.empty?
idx[-1] += 1
curr = self
puts 'popping'
idx.each { |i| puts i, curr.inspect; curr = curr[i] }
else
val = curr[idx.last]
if val.is_a?(Enumerable)
curr = val
idx << 0
else
yield val
idx[-1] += 1
end
end
end
end
def stack_flat(&block)
return to_enum(__method__) unless block_given?
stack = [self.each]
while enum = stack.last
begin
val = enum.next
if val.is_a?(Enumerable)
stack << val.each
else
yield val
end
rescue StopIteration
stack.pop
end
end
end
def recursive_flat(level = -1, &block)
return to_enum(__method__, level) unless block_given?
each do |val|
if val.is_a?(Enumerable)
val.recursive_flat(level - 1, &block)
else
yield val
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment