Skip to content

Commit

Permalink
feat: Add PopFunc to priorityqueue (#10)
Browse files Browse the repository at this point in the history
  • Loading branch information
idsulik authored Nov 24, 2024
1 parent 7347880 commit e68eca6
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 10 deletions.
24 changes: 15 additions & 9 deletions priorityqueue/priorityqueue.go
Original file line number Diff line number Diff line change
Expand Up @@ -68,16 +68,22 @@ func (pq *PriorityQueue[T]) Push(item T) {

// Pop removes and returns the highest priority item from the queue.
func (pq *PriorityQueue[T]) Pop() (T, bool) {
if len(pq.items) == 0 {
var zero T
return zero, false
return pq.PopFunc(func(T) bool { return true })
}

// PopFunc removes and returns the first item that satisfies the given function.
func (pq *PriorityQueue[T]) PopFunc(fn func(T) bool) (T, bool) {
for i, v := range pq.items {
if fn(v) {
last := len(pq.items) - 1
pq.items[i] = pq.items[last]
pq.items = pq.items[:last]
pq.down(i)
return v, true
}
}
top := pq.items[0]
last := len(pq.items) - 1
pq.items[0] = pq.items[last]
pq.items = pq.items[:last]
pq.down(0)
return top, true
var zero T
return zero, false
}

// Peek returns the highest priority item without removing it.
Expand Down
32 changes: 31 additions & 1 deletion priorityqueue/priorityqueue_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -260,7 +260,7 @@ type Task struct {
priority int
}

func TestCustomStruct(t *testing.T) {
func TestPopCustomStruct(t *testing.T) {
less := func(a, b Task) bool {
return a.priority < b.priority
}
Expand Down Expand Up @@ -295,6 +295,36 @@ func TestPopEmpty(t *testing.T) {
}
}

func TestPopFunc(t *testing.T) {
pq := NewOrdered[int]()

pq.Push(1)
pq.Push(2)
pq.Push(3)

item, ok := pq.PopFunc(
func(v int) bool {
return v == 2
},
)

if !ok {
t.Error("Expected to find and remove 2")
}
if item != 2 {
t.Errorf("Expected 2, got %d", item)
}

item, ok = pq.PopFunc(
func(v int) bool {
return v == 4
},
)
if ok {
t.Error("Did not expect to find 4")
}
}

func TestPeekEmpty(t *testing.T) {
less := func(a, b int) bool {
return a < b
Expand Down

0 comments on commit e68eca6

Please sign in to comment.