Package list golang-gopkg-eapache-queue.v1 / d4bdc2c
Merge pull request #10 from gammazero/master Get() accepts negative index. Evan Huus authored 4 years ago GitHub committed 4 years ago
2 changed file(s) with 21 addition(s) and 2 deletion(s). Raw diff Collapse all Expand all
6464 }
6565
6666 // Get returns the element at index i in the queue. If the index is
67 // invalid, the call will panic.
67 // invalid, the call will panic. This method accepts both positive and
68 // negative index values. Index 0 refers to the first element, and
69 // index -1 refers to the last.
6870 func (q *Queue) Get(i int) interface{} {
71 // If indexing backwards, convert to positive index.
72 if i < 0 {
73 i += q.count
74 }
6975 if i < 0 || i >= q.count {
7076 panic("queue: Get() called with index out of range")
7177 }
6868 }
6969 }
7070
71 func TestQueueGetNegative(t *testing.T) {
72 q := New()
73
74 for i := 0; i < 1000; i++ {
75 q.Add(i)
76 for j := 1; j <= q.Length(); j++ {
77 if q.Get(-j).(int) != q.Length()-j {
78 t.Errorf("index %d doesn't contain %d", -j, q.Length()-j)
79 }
80 }
81 }
82 }
83
7184 func TestQueueGetOutOfRangePanics(t *testing.T) {
7285 q := New()
7386
7689 q.Add(3)
7790
7891 assertPanics(t, "should panic when negative index", func() {
79 q.Get(-1)
92 q.Get(-4)
8093 })
8194
8295 assertPanics(t, "should panic when index greater than length", func() {