Skip to content

Commit

Permalink
Add Contains consumer
Browse files Browse the repository at this point in the history
  • Loading branch information
BooleanCat committed Sep 7, 2024
1 parent db0594e commit 9904dfa
Show file tree
Hide file tree
Showing 3 changed files with 36 additions and 0 deletions.
13 changes: 13 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -209,6 +209,19 @@ index, value, ok := itx.FromSlice([]int{1, 2, 3}).Enumerate().Find(func(index in
> [!TIP]
> The [filter package](it/filter/filter.go) contains some simple, pre-defined predicate functions.
### Contains

Contains consumes an iterator until the provided value is found, returning true if the value was
found or false if the iterator was exhausted.

```go
ok := it.Contains(slices.Values([]int{1, 2, 3}), 2)
```

<!-- prettier-ignore -->
> [!NOTE]
> The `itx` package does not contain `Contains` due to limitations with Go's type system.
### From, FromSlice, FromMap & Seq

The itx package contains some helper functions to convert iterators, slices or maps directly into
Expand Down
13 changes: 13 additions & 0 deletions it/iter.go
Original file line number Diff line number Diff line change
Expand Up @@ -179,3 +179,16 @@ func Len2[V, W any](iterator func(func(V, W) bool)) int {

return length
}

// Contains consumes an [iter.Seq] until the provided value is found and
// returns true. If the value is not found, it returns false when the iterator
// is exhausted.
func Contains[V comparable](iterator func(func(V) bool), v V) bool {
for value := range iterator {
if value == v {
return true
}
}

return false
}
10 changes: 10 additions & 0 deletions it/iter_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -187,3 +187,13 @@ func TestLen2Empty(t *testing.T) {

assert.Equal(t, it.Len2(it.Enumerate(it.Exhausted[int]())), 0)
}

func ExampleContains() {
numbers := slices.Values([]int{1, 2, 3})
fmt.Println(it.Contains(numbers, 2))
// Output: true
}

func TestContainsFalse(t *testing.T) {
assert.False(t, it.Contains(slices.Values([]int{1, 2, 3}), 4))
}

0 comments on commit 9904dfa

Please sign in to comment.