Skip to content

Commit 6c34ec6

Browse files
authored
Merge pull request #3 from ipfs/feat/peek
add Peek() method
2 parents 080776c + cbc2990 commit 6c34ec6

File tree

2 files changed

+22
-2
lines changed

2 files changed

+22
-2
lines changed

pq.go

+10-1
Original file line numberDiff line numberDiff line change
@@ -7,8 +7,10 @@ import "container/heap"
77
type PQ interface {
88
// Push adds the ele
99
Push(Elem)
10-
// Pop returns the highest priority Elem in PQ.
10+
// Pop removes and returns the highest priority Elem in PQ.
1111
Pop() Elem
12+
// Peek returns the highest priority Elem in PQ (without removing it).
13+
Peek() Elem
1214
// Len returns the number of elements in the PQ.
1315
Len() int
1416
// Update `fixes` the PQ.
@@ -56,6 +58,13 @@ func (w *wrapper) Pop() Elem {
5658
return heap.Pop(&w.heapinterface).(Elem)
5759
}
5860

61+
func (w *wrapper) Peek() Elem {
62+
if len(w.heapinterface.elems) == 0 {
63+
return nil
64+
}
65+
return w.heapinterface.elems[0].(Elem)
66+
}
67+
5968
func (w *wrapper) Update(index int) {
6069
heap.Fix(&w.heapinterface, index)
6170
}

pq_test.go

+12-1
Original file line numberDiff line numberDiff line change
@@ -51,14 +51,19 @@ func TestCorrectnessOfPop(t *testing.T) {
5151
q.Push(&e)
5252
}
5353
var priorities []int
54+
var peekPriorities []int
5455
for q.Len() > 0 {
5556
i := q.Pop().(*TestElem).Priority
5657
t.Logf("popped %v", i)
5758
priorities = append(priorities, i)
59+
peekPriorities = append(peekPriorities, i)
5860
}
59-
if !sort.IntsAreSorted(priorities) {
61+
if !sort.IntsAreSorted(peekPriorities) {
6062
t.Fatal("the values were not returned in sorted order")
6163
}
64+
if !sort.IntsAreSorted(priorities) {
65+
t.Fatal("the popped values were not returned in sorted order")
66+
}
6267
}
6368

6469
func TestUpdate(t *testing.T) {
@@ -73,12 +78,18 @@ func TestUpdate(t *testing.T) {
7378
q.Push(middle)
7479
q.Push(highest)
7580
q.Push(lowest)
81+
if q.Peek().(*TestElem).Key != highest.Key {
82+
t.Fatal("head element doesn't have the highest priority")
83+
}
7684
if q.Pop().(*TestElem).Key != highest.Key {
7785
t.Fatal("popped element doesn't have the highest priority")
7886
}
7987
q.Push(highest) // re-add the popped element
8088
highest.Priority = 0 // update the PQ
8189
q.Update(highest.Index()) // fix the PQ
90+
if q.Peek().(*TestElem).Key != middle.Key {
91+
t.Fatal("middle element should now have the highest priority")
92+
}
8293
if q.Pop().(*TestElem).Key != middle.Key {
8394
t.Fatal("middle element should now have the highest priority")
8495
}

0 commit comments

Comments
 (0)