Skip to content

Commit 9904dfa

Browse files
committed
Add Contains consumer
1 parent db0594e commit 9904dfa

File tree

3 files changed

+36
-0
lines changed

3 files changed

+36
-0
lines changed

README.md

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -209,6 +209,19 @@ index, value, ok := itx.FromSlice([]int{1, 2, 3}).Enumerate().Find(func(index in
209209
> [!TIP]
210210
> The [filter package](it/filter/filter.go) contains some simple, pre-defined predicate functions.
211211
212+
### Contains
213+
214+
Contains consumes an iterator until the provided value is found, returning true if the value was
215+
found or false if the iterator was exhausted.
216+
217+
```go
218+
ok := it.Contains(slices.Values([]int{1, 2, 3}), 2)
219+
```
220+
221+
<!-- prettier-ignore -->
222+
> [!NOTE]
223+
> The `itx` package does not contain `Contains` due to limitations with Go's type system.
224+
212225
### From, FromSlice, FromMap & Seq
213226

214227
The itx package contains some helper functions to convert iterators, slices or maps directly into

it/iter.go

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -179,3 +179,16 @@ func Len2[V, W any](iterator func(func(V, W) bool)) int {
179179

180180
return length
181181
}
182+
183+
// Contains consumes an [iter.Seq] until the provided value is found and
184+
// returns true. If the value is not found, it returns false when the iterator
185+
// is exhausted.
186+
func Contains[V comparable](iterator func(func(V) bool), v V) bool {
187+
for value := range iterator {
188+
if value == v {
189+
return true
190+
}
191+
}
192+
193+
return false
194+
}

it/iter_test.go

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -187,3 +187,13 @@ func TestLen2Empty(t *testing.T) {
187187

188188
assert.Equal(t, it.Len2(it.Enumerate(it.Exhausted[int]())), 0)
189189
}
190+
191+
func ExampleContains() {
192+
numbers := slices.Values([]int{1, 2, 3})
193+
fmt.Println(it.Contains(numbers, 2))
194+
// Output: true
195+
}
196+
197+
func TestContainsFalse(t *testing.T) {
198+
assert.False(t, it.Contains(slices.Values([]int{1, 2, 3}), 4))
199+
}

0 commit comments

Comments
 (0)