Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions changes/20251013111319.feature
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
:sparkles: `[collection]` Added a `Match` function
18 changes: 18 additions & 0 deletions utils/collection/search.go
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
14 changes: 14 additions & 0 deletions utils/collection/search_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
Loading