Unverified Commit 6c34ec60 authored by Steven Allen's avatar Steven Allen Committed by GitHub

Merge pull request #3 from ipfs/feat/peek

add Peek() method
parents 080776c4 cbc2990c
......@@ -7,8 +7,10 @@ import "container/heap"
type PQ interface {
// Push adds the ele
Push(Elem)
// Pop returns the highest priority Elem in PQ.
// Pop removes and returns the highest priority Elem in PQ.
Pop() Elem
// Peek returns the highest priority Elem in PQ (without removing it).
Peek() Elem
// Len returns the number of elements in the PQ.
Len() int
// Update `fixes` the PQ.
......@@ -56,6 +58,13 @@ func (w *wrapper) Pop() Elem {
return heap.Pop(&w.heapinterface).(Elem)
}
func (w *wrapper) Peek() Elem {
if len(w.heapinterface.elems) == 0 {
return nil
}
return w.heapinterface.elems[0].(Elem)
}
func (w *wrapper) Update(index int) {
heap.Fix(&w.heapinterface, index)
}
......
......@@ -51,14 +51,19 @@ func TestCorrectnessOfPop(t *testing.T) {
q.Push(&e)
}
var priorities []int
var peekPriorities []int
for q.Len() > 0 {
i := q.Pop().(*TestElem).Priority
t.Logf("popped %v", i)
priorities = append(priorities, i)
peekPriorities = append(peekPriorities, i)
}
if !sort.IntsAreSorted(priorities) {
if !sort.IntsAreSorted(peekPriorities) {
t.Fatal("the values were not returned in sorted order")
}
if !sort.IntsAreSorted(priorities) {
t.Fatal("the popped values were not returned in sorted order")
}
}
func TestUpdate(t *testing.T) {
......@@ -73,12 +78,18 @@ func TestUpdate(t *testing.T) {
q.Push(middle)
q.Push(highest)
q.Push(lowest)
if q.Peek().(*TestElem).Key != highest.Key {
t.Fatal("head element doesn't have the highest priority")
}
if q.Pop().(*TestElem).Key != highest.Key {
t.Fatal("popped element doesn't have the highest priority")
}
q.Push(highest) // re-add the popped element
highest.Priority = 0 // update the PQ
q.Update(highest.Index()) // fix the PQ
if q.Peek().(*TestElem).Key != middle.Key {
t.Fatal("middle element should now have the highest priority")
}
if q.Pop().(*TestElem).Key != middle.Key {
t.Fatal("middle element should now have the highest priority")
}
......
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment