Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
SimpleQueue
#!/usr/bin/env ruby
class SimpleQueue
def initialize(max)
@max = max
@queue = Array.new(max)
end
def clear
@queue = []
end
def empty?
@queue.empty?
end
def num_waitihg
raise NotImplementedError
end
def length
@queue.length
end
alias :size :length
def max
@max
end
def max=(n)
@max = n
end
def pop
@queue.shift
end
alias :shift :pop
alias :deq :pop
def push(*items)
items.each do |item|
@queue << item
if @queue.length > @max
@queue.shift
end
end
self
end
alias :<< :push
alias :enq :push
end
if $0 == __FILE__
eval DATA.read
end
__END__
require 'test/unit'
class SimpleQueueTest < Test::Unit::TestCase
def test_max
queue = SimpleQueue.new(5)
assert_equal 5, queue.max
queue.max = 10
assert_equal 10, queue.max
end
def test_enqueue
queue = SimpleQueue.new(5)
7.times do |n|
queue << n
end
assert_equal 5, queue.length
end
def test_dequeue
queue = SimpleQueue.new(5)
7.times do |n|
queue << n
end
assert_equal 2, queue.pop
end
def test_clear
queue = SimpleQueue.new(5)
7.times do |n|
queue << n
end
queue.clear
assert queue.empty?
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment