fn: add Filter to List

This commit adds an immutable Filter method to the linked List API.
This is useful because there are several instances wherein we iterate
through the linked List and only process a subset of it in some way
or another.
This commit is contained in:
Keagan McClelland
2024-09-10 17:40:48 -07:00
parent 779903af9d
commit f7264e6a5b
2 changed files with 108 additions and 0 deletions

View File

@@ -300,3 +300,18 @@ func (l *List[A]) PushFrontList(other *List[A]) {
n = n.Prev()
}
}
// Filter gives a slice of all of the node values that satisfy the given
// predicate.
func (l *List[A]) Filter(f Pred[A]) []A {
var acc []A
for cursor := l.Front(); cursor != nil; cursor = cursor.Next() {
a := cursor.Value
if f(a) {
acc = append(acc, a)
}
}
return acc
}