Skip to content

Commit

Permalink
Merge pull request #10 from gammazero/master
Browse files Browse the repository at this point in the history
Get() accepts negative index.
  • Loading branch information
eapache authored Aug 3, 2016
2 parents ded5959 + 04e142a commit d4bdc2c
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 2 deletions.
8 changes: 7 additions & 1 deletion queue.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
if i < 0 || i >= q.count {
panic("queue: Get() called with index out of range")
}
Expand Down
15 changes: 14 additions & 1 deletion queue_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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()

Expand All @@ -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() {
Expand Down

0 comments on commit d4bdc2c

Please sign in to comment.