Created
June 27, 2016 04:53
-
-
Save maetl/6c67c1f4a940736a88cb8df63f4eb2e4 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'fiber' | |
class Step | |
def initialize(source, yielder=nil) | |
@context = Fiber.new do | |
source.each do |element| | |
if yielder | |
yielder.call(element) | |
else | |
Fiber.yield(element) | |
end | |
end | |
end | |
end | |
def take(num) | |
to_enum.take(num) | |
end | |
def element | |
to_enum.next | |
end | |
def first | |
to_enum.next | |
end | |
def all | |
to_enum.to_a | |
end | |
def each | |
return to_enum unless block_given? | |
loop do | |
element = @context.resume | |
if @context.alive? | |
yield element | |
else | |
return | |
end | |
end | |
end | |
def map(&block) | |
yielder = -> (element) do | |
Fiber.yield(block.call(element)) | |
end | |
Step.new(self, yielder) | |
end | |
def filter(&block) | |
yielder = -> (element) do | |
Fiber.yield(element) if block.call(element) | |
end | |
Step.new(self, yielder) | |
end | |
end | |
source = Step.new(["a", "b", "c", "d", "e", "f"]) | |
result = source.map { |v| v.to_sym }.filter { |v| v != :a } | |
p result.take(2) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment