Sha256: 8e2720aaa3f57fd106b64e6098cec1ce3fc7c639cf11d5ea3aa9190c2c221ec6

Contents?: true

Size: 930 Bytes

Versions: 4

Compression:

Stored size: 930 Bytes

Contents

class Enumerator
  # Enumerate values produced from an initial state. The enumerator terminates when the next state is nil.
  # @param state [Object] The initial state
  # @yieldparam state [Object] the current state
  # @yieldreturn [Array] a 2-element array containing the next value and the next state
  def self.unfold(state)
    raise 'block is required' unless block_given?
    Enumerator.new do |y|
      unless state.nil?
        loop do
          next_value, state = yield(state)
          break if state.nil?
          y << next_value
        end
      end
    end
  end

  attr_accessor :__memo__, :__memo_instance__

  def memoized
    @__memo_instance__ ||= self.dup
    inner = __memo_instance__
    inner.__memo__ ||= []
    Enumerator.new do |y|
      i = 0
      loop do
        inner.__memo__ << inner.next while inner.__memo__.size <= i
        y << inner.__memo__[i]
        i += 1
      end
    end
  end
end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
abstractivator-0.20.0 lib/abstractivator/enumerator_ext.rb
abstractivator-0.19.0 lib/abstractivator/enumerator_ext.rb
abstractivator-0.18.0 lib/abstractivator/enumerator_ext.rb
abstractivator-0.17.0 lib/abstractivator/enumerator_ext.rb