Skip to content

Commit

Permalink
Merge pull request #7 from geniussportsgroup/develop
Browse files Browse the repository at this point in the history
Added Search method for searching first item meeting a condition
  • Loading branch information
lrleon committed Jul 19, 2021
2 parents d466986 + 2d9e375 commit ff4e385
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 1 deletion.
14 changes: 13 additions & 1 deletion functional.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {

Expand Down Expand Up @@ -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() {
Expand Down
14 changes: 14 additions & 0 deletions functional_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}

0 comments on commit ff4e385

Please sign in to comment.