types/views: add SliceContainsFunc like slices.ContainsFunc

Needed for a future change.

Updates #cleanup

Change-Id: I6d89ee8a048b3bb1eb9cfb2e5a53c93aed30b021
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
This commit is contained in:
Brad Fitzpatrick 2023-09-18 07:33:06 +01:00 committed by Brad Fitzpatrick
parent a61caea911
commit 98b5da47e8
2 changed files with 12 additions and 0 deletions

View File

@ -276,6 +276,16 @@ func SliceContains[T comparable](v Slice[T], e T) bool {
return false
}
// SliceContainsFunc reports whether f reports true for any element in v.
func SliceContainsFunc[T any](v Slice[T], f func(T) bool) bool {
for i := 0; i < v.Len(); i++ {
if f(v.At(i)) {
return true
}
}
return false
}
// SliceEqual is like the standard library's slices.Equal, but for two views.
func SliceEqual[T comparable](a, b Slice[T]) bool {
return slices.Equal(a.ж, b.ж)

View File

@ -124,6 +124,8 @@ func TestViewUtils(t *testing.T) {
c.Check(v.IndexFunc(func(s string) bool { return strings.HasPrefix(s, "z") }), qt.Equals, -1)
c.Check(SliceContains(v, "bar"), qt.Equals, true)
c.Check(SliceContains(v, "baz"), qt.Equals, false)
c.Check(SliceContainsFunc(v, func(s string) bool { return strings.HasPrefix(s, "f") }), qt.Equals, true)
c.Check(SliceContainsFunc(v, func(s string) bool { return len(s) > 3 }), qt.Equals, false)
c.Check(SliceEqualAnyOrder(v, v), qt.Equals, true)
c.Check(SliceEqualAnyOrder(v, SliceOf([]string{"bar", "foo"})), qt.Equals, true)
c.Check(SliceEqualAnyOrder(v, SliceOf([]string{"foo"})), qt.Equals, false)