Skip to content

Commit 47842c8

Browse files
GRbitgopherbot
authored andcommitted
slices: add ContainsFunc function
Since we have Index, IndexFunc, and Contains functions, it's logical to have ContainsFunc function as well. Fixes #53983 Change-Id: I1237d43bd93927d38b51e3e9ce5386b9098049f7 GitHub-Last-Rev: b7f6091 GitHub-Pull-Request: #39 Reviewed-on: https://go-review.googlesource.com/c/exp/+/417374 Run-TryBot: Ian Lance Taylor <[email protected]> Run-TryBot: Ian Lance Taylor <[email protected]> TryBot-Result: Gopher Robot <[email protected]> Reviewed-by: Michael Pratt <[email protected]> Reviewed-by: Ian Lance Taylor <[email protected]> Reviewed-by: Brad Fitzpatrick <[email protected]> Auto-Submit: Ian Lance Taylor <[email protected]>
1 parent 6dcec33 commit 47842c8

File tree

2 files changed

+25
-0
lines changed

2 files changed

+25
-0
lines changed

slices/slices.go

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -128,6 +128,12 @@ func Contains[E comparable](s []E, v E) bool {
128128
return Index(s, v) >= 0
129129
}
130130

131+
// ContainsFunc reports whether at least one
132+
// element e of s satisfies f(e).
133+
func ContainsFunc[E any](s []E, f func(E) bool) bool {
134+
return IndexFunc(s, f) >= 0
135+
}
136+
131137
// Insert inserts the values v... into s at index i,
132138
// returning the modified slice.
133139
// In the returned slice r, r[i] == v[0].

slices/slices_test.go

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -358,6 +358,25 @@ func TestContains(t *testing.T) {
358358
}
359359
}
360360

361+
func TestContainsFunc(t *testing.T) {
362+
for _, test := range indexTests {
363+
if got := ContainsFunc(test.s, equalToIndex(equal[int], test.v)); got != (test.want != -1) {
364+
t.Errorf("ContainsFunc(%v, equalToIndex(equal[int], %v)) = %t, want %t", test.s, test.v, got, test.want != -1)
365+
}
366+
}
367+
368+
s1 := []string{"hi", "HI"}
369+
if got := ContainsFunc(s1, equalToIndex(equal[string], "HI")); got != true {
370+
t.Errorf("ContainsFunc(%v, equalToContains(equal[string], %q)) = %t, want %t", s1, "HI", got, true)
371+
}
372+
if got := ContainsFunc(s1, equalToIndex(equal[string], "hI")); got != false {
373+
t.Errorf("ContainsFunc(%v, equalToContains(strings.EqualFold, %q)) = %t, want %t", s1, "hI", got, false)
374+
}
375+
if got := ContainsFunc(s1, equalToIndex(strings.EqualFold, "hI")); got != true {
376+
t.Errorf("ContainsFunc(%v, equalToContains(strings.EqualFold, %q)) = %t, want %t", s1, "hI", got, true)
377+
}
378+
}
379+
361380
var insertTests = []struct {
362381
s []int
363382
i int

0 commit comments

Comments
 (0)