Browse Source

Merge pull request #10 from gammazero/master

Get() accepts negative index.
Evan Huus 9 năm trước cách đây
mục cha
commit
d4bdc2c591
2 tập tin đã thay đổi với 21 bổ sung2 xóa
  1. 7 1
      queue.go
  2. 14 1
      queue_test.go

+ 7 - 1
queue.go

@@ -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")
 	}

+ 14 - 1
queue_test.go

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