Sha256: 046d890f6db8a3ef63e5aafd5d20abc7625c65828f10518dac77cd5dc7988ca3

Contents?: true

Size: 1.37 KB

Versions: 1

Compression:

Stored size: 1.37 KB

Contents

require 'facets/enumerator'
#require 'facets/enumerable/take'

# = Denumerable
#
# Classes which include Denumerable will get versions
# of map, select etc. which return a Denumerator, so that they work
# horizontally without creating intermediate arrays.
#
module Denumerable

  #
  def map
    Denumerator.new do |output|
      each do |*input|
        output.yield yield(*input)
      end
    end
  end
  alias :collect :map

  #
  def select
    Denumerator.new do |output|
      each do |*input|
        output.yield(*input) if yield(*input)
      end
    end
  end
  alias :find_all :select

  #
  def reject
    Denumerator.new do |output|
      each do |*input|
        output.yield(*input) unless yield(*input)
      end
    end
  end

  # Limit to the first n items in the list
  def take(n)
    Denumerator.new do |output|
      count = 0
      each do |*input|
        break if count >= n
        output.yield(*input)
        count += 1
      end
    end
  end

  # Skip the first n items in the list
  def skip(n)
    Denumerator.new do |output|
      count = 0
      each do |*input|
        output.yield(*input) if count >= n
        count += 1
      end
    end
  end

  # TODO: add more methods, e.g. grep, take_while etc.

end


# = Denumerator
#
# A class like Enumerator, but which has 'lazy' versions of map, select etc.
#
class Denumerator < Enumerator
  include Denumerable
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
facets-2.8.1 lib/core/facets/denumerable.rb