util/slicesx: add Filter function
For use in corp, where we appear to have re-implemented this in a few places with varying signatures. Signed-off-by: Andrew Dunham <andrew@du.nham.ca> Change-Id: Id863a87e674f3caa87945519be8e09650e9c1d76
This commit is contained in:
@ -77,3 +77,17 @@ func EqualSameNil[S ~[]E, E comparable](s1, s2 S) bool {
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// Filter calls fn with each element of the provided src slice, and appends the
|
||||
// element to dst if fn returns true.
|
||||
//
|
||||
// dst can be nil to allocate a new slice, or set to src[:0] to filter in-place
|
||||
// without allocating.
|
||||
func Filter[S ~[]T, T any](dst, src S, fn func(T) bool) S {
|
||||
for _, x := range src {
|
||||
if fn(x) {
|
||||
dst = append(dst, x)
|
||||
}
|
||||
}
|
||||
return dst
|
||||
}
|
||||
|
Reference in New Issue
Block a user