Skip to content

Commit

Permalink
Add Contains filter
Browse files Browse the repository at this point in the history
  • Loading branch information
BooleanCat committed Aug 26, 2024
1 parent bc4c7df commit bc8b604
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 0 deletions.
13 changes: 13 additions & 0 deletions it/filter/filter.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,10 @@
package filter

import (
"bytes"
"cmp"
"regexp"
"strings"
)

// IsEven returns true when the provided integer is even.
Expand Down Expand Up @@ -106,3 +108,14 @@ func Match[T string | []byte](pattern *regexp.Regexp) func(T) bool {
return pattern.MatchString(string(term))
}
}

// Contains returns a function that returns true when the provided string or
// byte slice is found within another string or byte slice. See
// [strings.Contains] and [bytes.Contains].
func Contains[T string | []byte](t T) func(T) bool {
if s, ok := any(t).(string); ok {
return func(v T) bool { return strings.Contains(any(v).(string), s) }
}

return func(v T) bool { return bytes.Contains(any(v).([]byte), any(t).([]byte)) }
}
20 changes: 20 additions & 0 deletions it/filter/filter_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -154,3 +154,23 @@ func ExampleMatch_bytes() {

// Output: foobar
}

func ExampleContains_string() {
strings := slices.Values([]string{"foobar", "barfoo"})

for element := range it.Filter(strings, filter.Contains("rfoo")) {
fmt.Println(element)
}

// Output: barfoo
}

func ExampleContains_bytes() {
strings := slices.Values([][]byte{[]byte("foobar"), []byte("barfoo")})

for element := range it.Filter(strings, filter.Contains([]byte("rfoo"))) {
fmt.Println(string(element))
}

// Output: barfoo
}

0 comments on commit bc8b604

Please sign in to comment.