-
Notifications
You must be signed in to change notification settings - Fork 0
/
combined_enumerator.rb
57 lines (44 loc) · 1.06 KB
/
combined_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
class CombinedOrderedEnumerator < Enumerator
class UnorderedEnumerator < RuntimeError
attr_reader :enumerator
def initialize(enumerator)
@enumerator = enumerator
end
end
def initialize(*enumerators)
@enumerators = enumerators
super() do |yielder|
while enumerators.any?
remove_empty_enumerators && next
raise UnorderedEnumerator.new(active_enumerator) unless on_ascending_order?
yielder.yield value
end
end
end
private
attr_accessor :enumerators
attr_reader :last_value
def value
@last_value = active_enumerator.next
end
def active_enumerator
enumerators.sort_by(&:peek).first
end
def remove_empty_enumerators
enumerators.reject! { |enumerator| is_empty? enumerator }
end
def is_empty?(enumerator)
enumerator.peek && false
rescue StopIteration
true
end
def on_ascending_order?
last_value_saved = last_value || NullValue.new
last_value_saved <= active_enumerator.peek
end
end
class NullValue
def <= other
true
end
end