Skip to content

Commit

Permalink
slices: add ContainsFunc function
Browse files Browse the repository at this point in the history
  • Loading branch information
GRbit committed Dec 1, 2022
1 parent b4a6d95 commit 96a32b3
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 0 deletions.
6 changes: 6 additions & 0 deletions slices/slices.go
Expand Up @@ -128,6 +128,12 @@ func Contains[E comparable](s []E, v E) bool {
return Index(s, v) >= 0
}

// ContainsFunc reports whether at least one
// element E of s satisfies f(E).
func ContainsFunc[E any](s []E, f func(E) bool) bool {
return IndexFunc(s, f) >= 0
}

// Insert inserts the values v... into s at index i,
// returning the modified slice.
// In the returned slice r, r[i] == v[0].
Expand Down
19 changes: 19 additions & 0 deletions slices/slices_test.go
Expand Up @@ -356,6 +356,25 @@ func TestContains(t *testing.T) {
}
}

func TestContainsFunc(t *testing.T) {
for _, test := range indexTests {
if got := ContainsFunc(test.s, equalToIndex(equal[int], test.v)); got != (test.want != -1) {
t.Errorf("ContainsFunc(%v, equalToIndex(equal[int], %v)) = %t, want %t", test.s, test.v, got, test.want != -1)
}
}

s1 := []string{"hi", "HI"}
if got := ContainsFunc(s1, equalToIndex(equal[string], "HI")); got != true {
t.Errorf("ContainsFunc(%v, equalToContains(equal[string], %q)) = %t, want %t", s1, "HI", got, true)
}
if got := ContainsFunc(s1, equalToIndex(equal[string], "hI")); got != false {
t.Errorf("ContainsFunc(%v, equalToContains(strings.EqualFold, %q)) = %t, want %t", s1, "hI", got, false)
}
if got := ContainsFunc(s1, equalToIndex(strings.EqualFold, "hI")); got != true {
t.Errorf("ContainsFunc(%v, equalToContains(strings.EqualFold, %q)) = %t, want %t", s1, "hI", got, true)
}
}

var insertTests = []struct {
s []int
i int
Expand Down

0 comments on commit 96a32b3

Please sign in to comment.