kinnell
3/13/2018 - 2:18 AM

Ordered Packet Emitter

Ordered Packet Emitter

class PacketEmitter
  def initialize
    testData = "DATA!"
    @packet_emitter = [ { number: 4, data:  testData }, { number: 0, data:  testData }, { number: 2, data:  testData }, { number: 1, data:  testData }, { number: 3, data:  testData } ]
    @number = -1
  end

  def next
    @number += 1
    @packet_emitter[@number]
  end
end

class OrderedPacketEmitter
  def initialize(packet_emitter)
    @packet_emitter = packet_emitter
    @ordered_packet_emitter = {}
    @number = 0
  end

  def next
    get_next_packet
    output_next_packet
    increment_number
  end

  private

  def get_next_packet
    while next_packet_needed?
      new_packet = @packet_emitter.next
      new_packet ? memoize_packet(new_packet) : return
    end
  end

  def memoize_packet(packet)
    @ordered_packet_emitter[packet[:number]] = packet
  end

  def next_packet_needed?
    @ordered_packet_emitter[@number].nil?
  end

  def output_next_packet
    puts @ordered_packet_emitter[@number] if @ordered_packet_emitter[@number]
  end

  def increment_number
    @number += 1
  end
end



test = PacketEmitter.new
# test.next

test2 = OrderedPacketEmitter.new(test)
test2.next
test2.next
test2.next
test2.next
test2.next
test2.next
test2.next
test2.next
test2.next
test2.next
test2.next
test2.next
test2.next
test2.next