diff --git a/functional.go b/functional.go index 1c2c222..9f25526 100644 --- a/functional.go +++ b/functional.go @@ -302,6 +302,18 @@ func Filter(seq Sequence, predicate func(interface{}) bool) *Seq.Slist { return ret } +// Search return the first item meeting predicate. If not found, then it return nil +func Search(seq Sequence, predicate func(interface{}) bool) interface{} { + + for it := seq.CreateIterator().(SequentialIterator); it.HasCurr(); it.Next() { + curr := it.GetCurr() + if predicate(curr) { + return curr + } + } + return nil +} + // Zip two lists into one list of pair. The result is truncated to the shortest list func Zip(s1, s2 Sequence) *Seq.Slist { @@ -355,7 +367,7 @@ func Split(seq Sequence, predicate func(item interface{}) bool) (*Seq.Slist, *Se return l1, l2 } -// Return the first item in seq satisfying predicate. If not item is found, the it returns nil +// Find Return the first item in seq satisfying predicate. If not item is found, the it returns nil func Find(seq Sequence, predicate func(item interface{}) bool) interface{} { for it := seq.CreateIterator().(SequentialIterator); it.HasCurr(); it.Next() { diff --git a/functional_test.go b/functional_test.go index 3271582..24e50ad 100644 --- a/functional_test.go +++ b/functional_test.go @@ -426,3 +426,17 @@ func TestTuple_Rotations(t *testing.T) { return pair.(Pair).Item1.(int) == pair.(Pair).Item2.(int) })) } + +func TestSearch(t *testing.T) { + + l := Seq.New(1, 2, 3, 4, 5, 6, 7, 8, 9, 0) + assert.Nil(t, Search(l, func(i interface{}) bool { + return i.(int) == 10 + })) + + val := Search(l, func(i interface{}) bool { + return i.(int) == 0 + }) + assert.NotNil(t, val) + assert.Equal(t, val.(int), 0) +}