Sha256: 3a0b10c96ccdb5271c4804bcf3911a2ffdd11a1759a2fdf13ca1b871359706bd

Contents?: true

Size: 1.43 KB

Versions: 6

Compression:

Stored size: 1.43 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.rewind
    Enumerator.new do |y|
      current_enumerator = empty_enumerator

      get_current_enumerator = ->() {
        until has_next(current_enumerator)
          return empty_enumerator unless has_next(enumerator)
          current_enumerator = enumerator.next.enumerator
          current_enumerator.rewind
        end
        current_enumerator
      }

      loop do
        current = get_current_enumerator.()
        if has_next(current)
          y << current.next
        else
          raise StopIteration.new
        end
      end
    end.lazy
  end

  def empty_enumerator
    [].lazy
  end
end

Version data entries

6 entries across 6 versions & 1 rubygems

Version Path
totally_lazy-0.1.56 lib/totally_lazy/enumerators.rb
totally_lazy-0.1.55 lib/totally_lazy/enumerators.rb
totally_lazy-0.1.54 lib/totally_lazy/enumerators.rb
totally_lazy-0.1.53 lib/totally_lazy/enumerators.rb
totally_lazy-0.1.52 lib/totally_lazy/enumerators.rb
totally_lazy-0.1.51 lib/totally_lazy/enumerators.rb