mirror of
https://github.com/rjNemo/underscore
synced 2026-06-06 02:26:42 +00:00
feat: find
This commit is contained in:
parent
3834edefb4
commit
6c6cf9ac68
3 changed files with 38 additions and 1 deletions
12
find.go
Normal file
12
find.go
Normal file
|
|
@ -0,0 +1,12 @@
|
|||
package underscore
|
||||
|
||||
import "errors"
|
||||
|
||||
func Find[T any](values []T, predicate func(T) bool) (res T, err error) {
|
||||
for _, v := range values {
|
||||
if predicate(v) {
|
||||
return v, nil
|
||||
}
|
||||
}
|
||||
return res, errors.New("value not found")
|
||||
}
|
||||
26
find_test.go
Normal file
26
find_test.go
Normal file
|
|
@ -0,0 +1,26 @@
|
|||
package underscore_test
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
u "github.com/rjNemo/underscore"
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
func TestFind(t *testing.T) {
|
||||
want := 5
|
||||
nums := []int{2, 4, 5, 6, 8, 0}
|
||||
isOdd := func(n int) bool { return n%2 != 0 }
|
||||
|
||||
got, err := u.Find(nums, isOdd)
|
||||
assert.Equal(t, want, got)
|
||||
assert.NoError(t, err)
|
||||
}
|
||||
|
||||
func TestNotFound(t *testing.T) {
|
||||
nums := []int{2, 4, 6, 8, 0}
|
||||
isOdd := func(n int) bool { return n%2 != 0 }
|
||||
|
||||
_, err := u.Find(nums, isOdd)
|
||||
assert.Error(t, err)
|
||||
}
|
||||
|
|
@ -13,5 +13,4 @@ func TestSome(t *testing.T) {
|
|||
isEven := func(n int) bool { return n%2 == 0 }
|
||||
|
||||
assert.True(t, u.Some(nums, isEven))
|
||||
|
||||
}
|
||||
|
|
|
|||
Loading…
Reference in a new issue