diff --git a/changes/20251013111319.feature b/changes/20251013111319.feature new file mode 100644 index 0000000000..bb1cfde74c --- /dev/null +++ b/changes/20251013111319.feature @@ -0,0 +1 @@ +:sparkles: `[collection]` Added a `Match` function diff --git a/utils/collection/search.go b/utils/collection/search.go index 003e1b9524..50ad8ad603 100644 --- a/utils/collection/search.go +++ b/utils/collection/search.go @@ -128,6 +128,24 @@ func Reject[S ~[]E, E any](s S, f FilterFunc[E]) S { return Filter(s, func(e E) bool { return !f(e) }) } +func match[E any](e E, matches []FilterFunc[E]) *Conditions { + conditions := NewConditions(len(matches)) + for i := range matches { + conditions.Add(matches[i](e)) + } + return &conditions +} + +// Match checks whether an element e matches any of the matching functions. +func Match[E any](e E, matches ...FilterFunc[E]) bool { + return match[E](e, matches).Any() +} + +// MatchAll checks whether an element e matches all the matching functions. +func MatchAll[E any](e E, matches ...FilterFunc[E]) bool { + return match[E](e, matches).All() +} + type ReduceFunc[T1, T2 any] func(T2, T1) T2 // Reduce runs a reducer function f over all elements in the array, in ascending-index order, and accumulates them into a single value. diff --git a/utils/collection/search_test.go b/utils/collection/search_test.go index f9b9b92240..be2f9f63f0 100644 --- a/utils/collection/search_test.go +++ b/utils/collection/search_test.go @@ -138,6 +138,20 @@ func TestFilterReject(t *testing.T) { })) } +func TestMatch(t *testing.T) { + match1 := func(i int) bool { return i == 1 } + match2 := func(i int) bool { return i == 2 } + match3 := func(i int) bool { return i == 3 } + assert.True(t, Match(1, match1, match2, match3)) + assert.True(t, Match(2, match1, match2, match3)) + assert.True(t, Match(3, match1, match2, match3)) + assert.False(t, Match(4, match1, match2, match3)) + assert.False(t, Match(0, match1, match2, match3)) + assert.False(t, Match(2, match1, match3)) + assert.True(t, MatchAll(1, match1)) + assert.False(t, MatchAll(1, match1, match2)) +} + func TestMap(t *testing.T) { mapped := Map([]int{1, 2}, func(i int) string { return fmt.Sprintf("Hello world %v", i)