class JSQueue

Attributes

first[RW]
last[RW]

Public Class Methods

new(data=nil) click to toggle source

Creates a new queue with an optional first item data.

If an initial value is provided, it will be considered both the first and last item in the queue.

# File lib/js_queue.rb, line 11
def initialize(data=nil)
  @first = QueueNode.new data unless data.nil?
  @first ||= nil
  @last = @first
end

Public Instance Methods

dequeue() click to toggle source

Removes and returns the data value of the first item in the queue.

Example

queue.dequeue # => 'I was first in line'
# File lib/js_queue.rb, line 36
def dequeue
  return if @first.nil?
  data = @first.data
  @first = @first.next unless @first.nil?
  @last = nil if @first.nil?
  data
end
empty?() click to toggle source

Returns a Boolean indicating whether the queue has any items.

Example

queue.empty? # => false
# File lib/js_queue.rb, line 58
def empty?
  first.nil?
end
enqueue(data) click to toggle source

Adds the provided value data to the back of the queue.

If it is the only item in the queue, it will be considered both the first and the last.

# File lib/js_queue.rb, line 22
def enqueue(data)
  node = QueueNode.new data
  unless last.nil?
    @last.next = node
    @last = node
  end
  @first = node if @first.nil?
end
peek() click to toggle source

Returns the first enqueued item's value, without removing it.

Example

queue.peek # => 'I am first in line'
# File lib/js_queue.rb, line 49
def peek
  first.nil? ? nil : first.data
end