From 98b5da47e891f312696bd1409a7774d6b99babd1 Mon Sep 17 00:00:00 2001 From: Brad Fitzpatrick Date: Mon, 18 Sep 2023 07:33:06 +0100 Subject: [PATCH] types/views: add SliceContainsFunc like slices.ContainsFunc Needed for a future change. Updates #cleanup Change-Id: I6d89ee8a048b3bb1eb9cfb2e5a53c93aed30b021 Signed-off-by: Brad Fitzpatrick --- types/views/views.go | 10 ++++++++++ types/views/views_test.go | 2 ++ 2 files changed, 12 insertions(+) diff --git a/types/views/views.go b/types/views/views.go index 117e80adc..5a1671250 100644 --- a/types/views/views.go +++ b/types/views/views.go @@ -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.ж) diff --git a/types/views/views_test.go b/types/views/views_test.go index 93cda30e5..2098b9f47 100644 --- a/types/views/views_test.go +++ b/types/views/views_test.go @@ -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)