From 9904dfad9973cf7b203bc07e66960271b36f09f6 Mon Sep 17 00:00:00 2001 From: Tom Godkin Date: Sat, 7 Sep 2024 22:33:52 +0100 Subject: [PATCH] Add Contains consumer --- README.md | 13 +++++++++++++ it/iter.go | 13 +++++++++++++ it/iter_test.go | 10 ++++++++++ 3 files changed, 36 insertions(+) diff --git a/README.md b/README.md index 0288d8b..b9450de 100644 --- a/README.md +++ b/README.md @@ -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) +``` + + +> [!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 diff --git a/it/iter.go b/it/iter.go index b4aa290..3424b1e 100644 --- a/it/iter.go +++ b/it/iter.go @@ -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 +} diff --git a/it/iter_test.go b/it/iter_test.go index a2442a9..c0723d6 100644 --- a/it/iter_test.go +++ b/it/iter_test.go @@ -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)) +}