-
Notifications
You must be signed in to change notification settings - Fork 85
/
Copy pathenumerator.rb
123 lines (102 loc) · 2.15 KB
/
enumerator.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
class Enumerator
include Enumerable
def initialize(obj = nil, method = :each, *args, &block)
obj = Generator.new(&block) if obj.nil?
@object = obj
@method = method.to_sym
@args = args
self
end
def each(&block)
if block
@object.send(@method, *@args, &block)
else
self
end
end
def each_with_index(&block)
return self.enum_for(:each_with_index) unless block
i = 0
self.each do |*e|
v = (e.size == 1) ? e[0] : e
val = yield(v, i)
i += 1
val
end
end
def with_index(offset = nil, &block)
return self.enum_for(:with_index, offset) unless block
offset = offset ? Topaz.convert_type(offset, Fixnum, :to_int) : 0
i = offset
self.each do |*e|
v = (e.size == 1) ? e[0] : e
val = yield(v, i)
i += 1
val
end
end
def rewind
@object.rewind if @object.respond_to?(:rewind)
@nextvals = nil
@fiber = nil
@finished = false
self
end
def peek
if @nextvals.nil?
@nextvals = []
@finished = false
@fiber ||= Fiber.new do
self.each do |*values|
Fiber.yield(*values)
end
@finished = true
end
end
if @nextvals.empty?
@nextvals << @fiber.resume
raise StopIteration.new("iteration reached an end") if @finished
end
return @nextvals.first
end
def peek_values
return Array(self.peek)
end
def next
raise StopIteration.new("iteration reached an end") if @finished
self.peek
return @nextvals.shift
end
def next_values
return Array(self.next)
end
def with_object(obj, &block)
return Enumerator.new(self, :with_object, obj) unless block
self.each { |*v| yield(*v, obj) }
return obj
end
class Generator
include Enumerable
def initialize(&block)
@block = block
self
end
def each
proc = Proc.new { |*args| yield(*args) }
@block.call(Yielder.new(&proc))
end
end
class Yielder
def initialize(&block)
@block = block
self
end
def yield(*args)
@block.call(*args)
end
def <<(val)
self.yield val
self
end
end
end