Class: Evidence::MergedStream

Inherits:
Object
  • Object
show all
Includes:
Enumerable
Defined in:
lib/evidence/stream.rb

Instance Method Summary collapse

Constructor Details

#initialize(streams, comparator) ⇒ MergedStream

Returns a new instance of MergedStream.



58
59
60
61
# File 'lib/evidence/stream.rb', line 58

def initialize(streams, comparator)
  @comparator = comparator
  @heads = streams.map{|s| {stream: s}}
end

Instance Method Details

#each(&block) ⇒ Object



67
68
69
70
71
72
73
74
75
76
77
# File 'lib/evidence/stream.rb', line 67

def each(&block)
  pull_heads
  loop do
    if min = @heads.min{|a, b| @comparator.call(a[:element], b[:element])}
      block.call(min.delete(:element).tap{ pull_heads })
    else
      break if @heads.empty?
      pull_heads
    end
  end
end

#eos?Boolean

Returns:

  • (Boolean)


63
64
65
# File 'lib/evidence/stream.rb', line 63

def eos?
  @heads.empty?
end

#pull(stream) ⇒ Object



83
84
85
86
87
88
89
90
# File 'lib/evidence/stream.rb', line 83

def pull(stream)
  loop do
    return nil if stream.eos?
    if n = stream.first
      return n
    end
  end
end

#pull_headsObject



79
80
81
# File 'lib/evidence/stream.rb', line 79

def pull_heads
  @heads.select!{|h| h[:element] ||= pull(h[:stream])}
end