Sha256: 2a25477ef671df2a3ec8ccbbacf4b35500dda1e626407aeb580299278fec4233

Contents?: true

Size: 1.34 KB

Versions: 25

Compression:

Stored size: 1.34 KB

Contents

module Enumerators
  private
  def reverse_enumerator(e)
    e.reverse_each
  end

  def has_next(e)
    begin
      e.peek
      true
    rescue StopIteration
      false
    end
  end

  def enumerator_of(fn, init)
    Enumerator.new do |y|
      value = init
      y << value
      loop do
        value = fn.(value)
        y << value
      end
    end.lazy
  end

  def repeat_fn_enumerator(fn)
    Enumerator.new do |y|
      loop do
        y << fn.()
      end
    end.lazy
  end

  def repeat_enumerator(value)
    repeat_fn_enumerator(returns(value))
  end

  def character_enumerator(string)
    Enumerator.new do |y|
      index = 0
      loop do
        raise StopIteration.new unless index < string.size
        y << string[index]
        index = index + 1
      end
    end.lazy
  end

  def flatten_enumerator(enumerator)
    Enumerator.new do |y|
      current_enumerator = empty_enumerator

      loop do
        until has_next(current_enumerator)
          unless has_next(enumerator)
            current_enumerator = empty_enumerator
            break
          end
          current_enumerator = enumerator.next.enumerator
        end

        if has_next(current_enumerator)
          y << current_enumerator.next
        else
          raise StopIteration.new
        end
      end
    end.lazy
  end

  def empty_enumerator
    [].lazy
  end
end

Version data entries

25 entries across 25 versions & 1 rubygems

Version Path
totally_lazy-0.1.49 lib/totally_lazy/enumerators.rb
totally_lazy-0.1.48 lib/totally_lazy/enumerators.rb
totally_lazy-0.1.47 lib/totally_lazy/enumerators.rb
totally_lazy-0.1.46 lib/totally_lazy/enumerators.rb
totally_lazy-0.1.45 lib/totally_lazy/enumerators.rb
totally_lazy-0.1.44 lib/totally_lazy/enumerators.rb
totally_lazy-0.1.43 lib/totally_lazy/enumerators.rb
totally_lazy-0.1.42 lib/totally_lazy/enumerators.rb
totally_lazy-0.1.41 lib/totally_lazy/enumerators.rb
totally_lazy-0.1.39 lib/totally_lazy/enumerators.rb
totally_lazy-0.1.38 lib/totally_lazy/enumerators.rb
totally_lazy-0.1.37 lib/totally_lazy/enumerators.rb
totally_lazy-0.1.36 lib/totally_lazy/enumerators.rb
totally_lazy-0.1.35 lib/totally_lazy/enumerators.rb
totally_lazy-0.1.34 lib/totally_lazy/enumerators.rb
totally_lazy-0.1.33 lib/totally_lazy/enumerators.rb
totally_lazy-0.1.32 lib/totally_lazy/enumerators.rb
totally_lazy-0.1.31 lib/totally_lazy/enumerators.rb
totally_lazy-0.1.30 lib/totally_lazy/enumerators.rb
totally_lazy-0.1.29 lib/totally_lazy/enumerators.rb