Skip to content
Browse files

Merge pull request #6 from elaforc/add-queue-tests

Added rpsec tests for queue - 24pullrequests
  • Loading branch information...
2 parents 4e2ebed + c74daed commit 4cfac673259118301d0218ad243c250f0c65b16e @samdunne committed Dec 8, 2012
Showing with 72 additions and 7 deletions.
  1. +5 −1 lib/rdata.rb
  2. +19 −6 lib/rdata/queue.rb
  3. +48 −0 spec/queue_spec.rb
  4. 0 spec/{rdata_spec.rb → stack_spec.rb}
View
6 lib/rdata.rb
@@ -1,8 +1,12 @@
require 'rdata/version'
require "rdata/stack.rb"
+require "rdata/queue.rb"
module RData
def self.Stack
Stack.new
end
-end
+ def self.Queue
+ Queue.new
+ end
+end
View
25 lib/rdata/queue.rb
@@ -4,20 +4,33 @@ class Queue
def initialize
@queue = Array[]
- @head, @tail = 0
+ @head = 0
+ @tail = 0
end
def enqueue(x)
@queue[@tail] = x
- @tail = (@tail == @length) ? 1 : @tail - 1
+ @tail = (@tail == @length) ? 1 : @tail + 1
end
def dequeue
- x = @head
- @head = (@head == @length) ? 1 : @head + 1
- return x
+ if self.is_empty? == "true"
+ raise '[underflow] Cannot dequeue data from an empty queue'
+ else
+ x = @queue[@head]
+ @head = (@head == @length) ? 1 : @head + 1
+ return x
+ end
end
+ def peek
+ return @queue[@head]
+ end
+
+ def is_empty?
+ (@head == 0 && @tail == 0) ? 'true' : 'false'
+ end
+
end
-end
+end
View
48 spec/queue_spec.rb
@@ -0,0 +1,48 @@
+require 'spec_helper'
+
+describe RData::Queue do
+
+ let(:queue) { RData.Queue }
+
+ context "An empty queue" do
+
+ it "should be empty" do
+ queue.is_empty?.should eql("true")
+ end
+
+ it "should enqueue an element" do
+ queue.enqueue(9)
+ queue.peek.should eql(9)
+ end
+
+ it "should raise an error when dequeueing from an empty queue" do
+ expect {
+ queue.dequeue
+ }.to raise_error(StandardError)
+ end
+ end
+
+ context "A queue with elements" do
+ before(:each) do
+ queue.enqueue(5)
+ queue.enqueue(8)
+ end
+
+ it "should not be empty" do
+ queue.is_empty?.should eql("false")
+ end
+
+ it "should reveal the first element" do
+ queue.peek.should eql(5)
+ end
+
+ it "should dequeue the first element" do
+ queue.dequeue
+ queue.peek.should eql(8)
+ end
+
+ end
+
+end
+
+
View
0 spec/rdata_spec.rb → spec/stack_spec.rb
File renamed without changes.

0 comments on commit 4cfac67

Please sign in to comment.
Something went wrong with that request. Please try again.