Sha256: 63ec675c42f122044db13531fbd23fdd28e13b236f309592f0314af09f1c0da3

Contents?: true

Size: 1.33 KB

Versions: 15

Compression:

Stored size: 1.33 KB

Contents

module Enumerators
  def reverse(e)
    e.reverse_each
  end

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

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

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

  def repeat_fn_enumerator(fn)
    Enumerator.new do |y|
      loop do
        y << fn.()
      end
    end.lazy
  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

15 entries across 15 versions & 1 rubygems

Version Path
totally_lazy-0.1.22 lib/enumerators.rb
totally_lazy-0.1.21 lib/enumerators.rb
totally_lazy-0.1.20 lib/enumerators.rb
totally_lazy-0.1.19 lib/enumerators.rb
totally_lazy-0.1.18 lib/enumerators.rb
totally_lazy-0.1.17 lib/enumerators.rb
totally_lazy-0.1.16 lib/enumerators.rb
totally_lazy-0.1.15 lib/enumerators.rb
totally_lazy-0.1.14 lib/enumerators.rb
totally_lazy-0.1.13 lib/enumerators.rb
totally_lazy-0.1.12 lib/enumerators.rb
totally_lazy-0.1.11 lib/enumerators.rb
totally_lazy-0.1.10 lib/enumerators.rb
totally_lazy-0.1.9 lib/enumerators.rb
totally_lazy-0.1.0 lib/enumerators.rb