Skip to content

Commit

Permalink
Merge pull request samber#60 from muety/muety/patch1
Browse files Browse the repository at this point in the history
Adding FindOrElse and tests
  • Loading branch information
samber committed Apr 11, 2022
2 parents 3c534e5 + fc06d10 commit 00f674c
Show file tree
Hide file tree
Showing 4 changed files with 45 additions and 3 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -216,7 +216,7 @@ present := lo.Contains[int]([]int{0, 1, 2, 3, 4, 5}, 5)
// true
```

### Contains
### ContainsBy

Returns true if the predicate function returns `true`.

Expand Down
14 changes: 12 additions & 2 deletions find.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,9 @@ package lo

import (
"fmt"
"golang.org/x/exp/constraints"
"math"
"math/rand"

"golang.org/x/exp/constraints"
)

// import "golang.org/x/exp/constraints"
Expand Down Expand Up @@ -76,6 +75,17 @@ func FindLastIndexOf[T any](collection []T, predicate func(T) bool) (T, int, boo
return result, -1, false
}

// FindOrElse search an element in a slice based on a predicate. It returns the element if found or a given fallback value otherwise.
func FindOrElse[T any](collection []T, fallback T, predicate func(T) bool) T {
for _, item := range collection {
if predicate(item) {
return item
}
}

return fallback
}

// Min search the minimum value of a collection.
func Min[T constraints.Ordered](collection []T) T {
var min T
Expand Down
14 changes: 14 additions & 0 deletions find_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,20 @@ func TestFindLastIndexOf(t *testing.T) {
is.Equal(index2, -1)
}

func TestFindOrElse(t *testing.T) {
is := assert.New(t)

result1 := FindOrElse[string]([]string{"a", "b", "c", "d"}, "x", func(i string) bool {
return i == "b"
})
result2 := FindOrElse[string]([]string{"foobar"}, "x", func(i string) bool {
return i == "b"
})

is.Equal(result1, "b")
is.Equal(result2, "x")
}

func TestMin(t *testing.T) {
is := assert.New(t)

Expand Down
18 changes: 18 additions & 0 deletions slice_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,24 @@ func TestReduce(t *testing.T) {
is.Equal(result2, 20)
}

func TestForEach(t *testing.T) {
is := assert.New(t)

// check of callback is called for every element and in proper order

callParams1 := []string{}
callParams2 := []int{}

ForEach[string]([]string{"a", "b", "c"}, func(item string, i int) {
callParams1 = append(callParams1, item)
callParams2 = append(callParams2, i)
})

is.ElementsMatch([]string{"a", "b", "c"}, callParams1)
is.ElementsMatch([]int{0, 1, 2}, callParams2)
is.IsIncreasing(callParams2)
}

func TestUniq(t *testing.T) {
is := assert.New(t)

Expand Down

0 comments on commit 00f674c

Please sign in to comment.