util/slicesx: add AppendMatching

We had this in a different repo, but moving it here, as this a more
fitting package.

Updates #cleanup

Change-Id: I5fb9b10e465932aeef5841c67deba4d77d473d57
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
pull/11948/head
Brad Fitzpatrick 7 months ago committed by Brad Fitzpatrick
parent fe009c134e
commit 7455e027e9

@ -91,3 +91,13 @@ func Filter[S ~[]T, T any](dst, src S, fn func(T) bool) S {
}
return dst
}
// AppendMatching appends elements in ps to dst if f(x) is true.
func AppendMatching[T any](dst, ps []T, f func(T) bool) []T {
for _, p := range ps {
if f(p) {
dst = append(dst, p)
}
}
return dst
}

@ -136,3 +136,18 @@ func TestFilterNoAllocations(t *testing.T) {
t.Fatalf("got %.4f allocs, want 1", allocs)
}
}
func TestAppendMatching(t *testing.T) {
v := []string{"one", "two", "three", "four"}
got := AppendMatching(v[:0], v, func(s string) bool { return len(s) > 3 })
want := []string{"three", "four"}
if !reflect.DeepEqual(got, want) {
t.Errorf("got %v; want %v", got, want)
}
wantOrigMem := []string{"three", "four", "three", "four"}
if !reflect.DeepEqual(v, wantOrigMem) {
t.Errorf("got %v; want %v", v, wantOrigMem)
}
}

Loading…
Cancel
Save