File tree Expand file tree Collapse file tree 2 files changed +21
-2
lines changed
Expand file tree Collapse file tree 2 files changed +21
-2
lines changed Original file line number Diff line number Diff line change @@ -65,8 +65,14 @@ func (q *Queue) Peek() interface{} {
6565}
6666
6767// Get returns the element at index i in the queue. If the index is
68- // invalid, the call will panic.
68+ // invalid, the call will panic. This method accepts both positive and
69+ // negative index values. Index 0 refers to the first element, and
70+ // index -1 refers to the last.
6971func (q * Queue ) Get (i int ) interface {} {
72+ // If indexing backwards, convert to positive index.
73+ if i < 0 {
74+ i = q .count + i
75+ }
7076 if i < 0 || i >= q .count {
7177 panic ("queue: Get() called with index out of range" )
7278 }
Original file line number Diff line number Diff line change @@ -69,6 +69,19 @@ func TestQueueGet(t *testing.T) {
6969 }
7070}
7171
72+ func TestQueueGetNegative (t * testing.T ) {
73+ q := New ()
74+
75+ for i := 0 ; i < 1000 ; i ++ {
76+ q .Add (i )
77+ for j := 1 ; j <= q .Length (); j ++ {
78+ if q .Get (- j ).(int ) != q .Length ()- j {
79+ t .Errorf ("index %d doesn't contain %d" , - j , q .Length ()- j )
80+ }
81+ }
82+ }
83+ }
84+
7285func TestQueueGetOutOfRangePanics (t * testing.T ) {
7386 q := New ()
7487
@@ -77,7 +90,7 @@ func TestQueueGetOutOfRangePanics(t *testing.T) {
7790 q .Add (3 )
7891
7992 assertPanics (t , "should panic when negative index" , func () {
80- q .Get (- 1 )
93+ q .Get (- 4 )
8194 })
8295
8396 assertPanics (t , "should panic when index greater than length" , func () {
You can’t perform that action at this time.
0 commit comments