Method: BinaryParser::StreamTemplateBase#accumulate

Defined in:
lib/stream_template_base.rb

#accumulate(init_amount, dest_amount, &reduce_proc) ⇒ Object

Accumulate elements Concrete example:

If stream has [1, 2, 3, 4, 5, ...] and given reduce_proc is Proc.new{|acc, a| acc + a},
accumulate(0, 6, &reduce_proc) returns array of [1, 2, 3] and then stream has[4, 5, ...].

Special case: If enough elements don’t remain, this method returns nil.

Example: [1, 2, 3], accumulate(0, 7, &reduce_proc) => return: nil, stream: [] (end)


136
137
138
139
140
141
142
143
144
145
# File 'lib/stream_template_base.rb', line 136

def accumulate(init_amount, dest_amount, &reduce_proc)
  raise BadManipulationError, "Reduce Proc isn't given." unless reduce_proc
  accumulation, amount = [], init_amount
  while amount < dest_amount
    return nil unless rest?
    accumulation << get_next
    amount = reduce_proc.call(amount, accumulation.last)
  end
  return accumulation
end