From 98ef0e8da99dc5704f6a33070fd1671b271cf048 Mon Sep 17 00:00:00 2001 From: Andrew Gillis Date: Wed, 3 Aug 2016 13:27:42 -0400 Subject: [PATCH 1/2] Get() accepts negative index. --- queue.go | 8 +++++++- queue_test.go | 15 ++++++++++++++- 2 files changed, 21 insertions(+), 2 deletions(-) diff --git a/queue.go b/queue.go index 2dc8d93..6fe6ca8 100644 --- a/queue.go +++ b/queue.go @@ -65,8 +65,14 @@ func (q *Queue) Peek() interface{} { } // Get returns the element at index i in the queue. If the index is -// invalid, the call will panic. +// invalid, the call will panic. This method accepts both positive and +// negative index values. Index 0 refers to the first element, and +// index -1 refers to the last. func (q *Queue) Get(i int) interface{} { + // If indexing backwards, convert to positive index. + if i < 0 { + i = q.count + i + } if i < 0 || i >= q.count { panic("queue: Get() called with index out of range") } diff --git a/queue_test.go b/queue_test.go index f2765c1..213c3c7 100644 --- a/queue_test.go +++ b/queue_test.go @@ -69,6 +69,19 @@ func TestQueueGet(t *testing.T) { } } +func TestQueueGetNegative(t *testing.T) { + q := New() + + for i := 0; i < 1000; i++ { + q.Add(i) + for j := 1; j <= q.Length(); j++ { + if q.Get(-j).(int) != q.Length()-j { + t.Errorf("index %d doesn't contain %d", -j, q.Length()-j) + } + } + } +} + func TestQueueGetOutOfRangePanics(t *testing.T) { q := New() @@ -77,7 +90,7 @@ func TestQueueGetOutOfRangePanics(t *testing.T) { q.Add(3) assertPanics(t, "should panic when negative index", func() { - q.Get(-1) + q.Get(-4) }) assertPanics(t, "should panic when index greater than length", func() { From 04e142afea9877976c7b0f9c9049fb2c58795498 Mon Sep 17 00:00:00 2001 From: Andrew Gillis Date: Wed, 3 Aug 2016 14:07:53 -0400 Subject: [PATCH 2/2] += notation --- queue.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/queue.go b/queue.go index 6fe6ca8..6b79323 100644 --- a/queue.go +++ b/queue.go @@ -71,7 +71,7 @@ func (q *Queue) Peek() interface{} { func (q *Queue) Get(i int) interface{} { // If indexing backwards, convert to positive index. if i < 0 { - i = q.count + i + i += q.count } if i < 0 || i >= q.count { panic("queue: Get() called with index out of range")