class ScanLeft

Wraps any Enumerable to provide the {#scan_left} operation.

Please see {file:README.md} for details, examples, background, and further reading about this operation.

Note: if you'd prefer to use the {#scan_left} method directly on any Enumerable instance, please see the optional refinement {EnumerableWithScanLeft}.

@example

ScanLeft.new([1, 2, 3]).scan_left(0) { |s, x| s + x } == [0, 1, 3, 6]

@see EnumerableWithScanLeft

Constants

VERSION

Attributes

enumerable[R]

@return [Enumerable] Enumerable to transform via {#scan_left}

Public Class Methods

new(enumerable) click to toggle source

@param enumerable [Enumerable] Enumerable to transform via {#scan_left}

# File lib/scan_left.rb, line 26
def initialize(enumerable)
  @enumerable = enumerable
end

Public Instance Methods

scan_left(initial) { |memo, *obj| ... } click to toggle source

Map the enumerable to the incremental state of a calculation by applying the given block, in turn, to each element and the previous state of the calculation, resulting in an enumerable of the state after each iteration.

@return [Enumerable] Generate a stream of intermediate states

resulting from applying a binary operator. Equivalent to a
stream of +#inject+ calls on first N elements, increasing N from
zero to the size of the stream. NOTE: Preserves laziness if
+enumerable+ is lazy.

@param initial [Object] Initial state value to yield.

@yield [memo, obj] Invokes given block with previous state value

+memo+ and next element of the stream +obj+.

@yieldreturn [Object] The next state value for memo.

# File lib/scan_left.rb, line 47
def scan_left(initial)
  memo = initial
  outs = enumerable.map { |*obj| memo = yield(memo, *obj) }
  prepend_preserving_laziness(value: initial, enum: outs)
end

Private Instance Methods

prepend_preserving_laziness(value:, enum:) click to toggle source
# File lib/scan_left.rb, line 55
def prepend_preserving_laziness(value:, enum:)
  case enum
  when Enumerator::Lazy
    [[value], enum].lazy.flat_map { |x| x }
  else
    [value] + enum
  end
end