Skip to content

Commit 98ef0e8

Browse files
committed
Get() accepts negative index.
1 parent ded5959 commit 98ef0e8

File tree

2 files changed

+21
-2
lines changed

2 files changed

+21
-2
lines changed

queue.go

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff 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.
6971
func (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
}

queue_test.go

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff 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+
7285
func 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() {

0 commit comments

Comments
 (0)