Merge pull request #10 from gammazero/master
Get() accepts negative index.
Evan Huus authored 7 years ago
GitHub committed 7 years ago
64 | 64 |
}
|
65 | 65 |
|
66 | 66 |
// 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.
|
68 | 70 |
func (q *Queue) Get(i int) interface{} {
|
|
71 |
// If indexing backwards, convert to positive index.
|
|
72 |
if i < 0 {
|
|
73 |
i += q.count
|
|
74 |
}
|
69 | 75 |
if i < 0 || i >= q.count {
|
70 | 76 |
panic("queue: Get() called with index out of range")
|
71 | 77 |
}
|
68 | 68 |
}
|
69 | 69 |
}
|
70 | 70 |
|
|
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 |
|
71 | 84 |
func TestQueueGetOutOfRangePanics(t *testing.T) {
|
72 | 85 |
q := New()
|
73 | 86 |
|
|
76 | 89 |
q.Add(3)
|
77 | 90 |
|
78 | 91 |
assertPanics(t, "should panic when negative index", func() {
|
79 | |
q.Get(-1)
|
|
92 |
q.Get(-4)
|
80 | 93 |
})
|
81 | 94 |
|
82 | 95 |
assertPanics(t, "should panic when index greater than length", func() {
|