Created
October 27, 2011 07:25
-
-
Save kyanny/1318971 to your computer and use it in GitHub Desktop.
SimpleQueue
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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