diff --git a/queue.go b/queue.go index 2dc8d93..6fe6ca8 100644 --- a/queue.go +++ b/queue.go @@ -65,8 +65,14 @@ } // 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 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 @@ 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() {