Top Level Namespace

Instance Method Summary collapse

Instance Method Details

#join_sorted(iterators) ⇒ Object



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
# File 'lib/join-iterator.rb', line 1

def join_sorted(iterators)
  iterators = iterators.map(&:to_enum)
  values = []
  keys = []
  iterators.each_with_index do |iterator, index|
    begin
      kv = iterator.next
      values[index] = kv[1]
      keys[index] = kv[0]
    rescue StopIteration
      values[index] = nil
      keys[index] = nil
      iterators[index] = nil
    end
  end

  until iterators.map{|x| x == nil}.all?
    line = []
    min_key = keys.select{|x| x != nil }.min
    keys.each_with_index do |key, index| 
      if key == min_key
        line << values[index]

        begin
          kv = iterators[index].next
          values[index] = kv[1]
          keys[index] = kv[0]
        rescue StopIteration
          values[index] = nil
          keys[index] = nil
          iterators[index] = nil
        end
      else
        line << nil
      end
    end

    yield [min_key, line]
  end 
end