diff --git a/mr/search.go b/mr/search.go index af8d82a..ca71795 100644 --- a/mr/search.go +++ b/mr/search.go @@ -4,6 +4,7 @@ func zero[T any]() (v T) { return } +// Find returns the first element in the slice that satisfies the provided testing function. Otherwise zero value is returned. func Find[T any](arr []T, predict func(T) bool) T { for _, v := range arr { if predict(v) { @@ -13,6 +14,7 @@ func Find[T any](arr []T, predict func(T) bool) T { return zero[T]() } +// FindP returns the first element in the slice that satisfies the provided testing function. Otherwise nil is returned. func FindP[T any](arr []T, predict func(*T) bool) *T { for _, v := range arr { if predict(&v) { @@ -21,3 +23,13 @@ func FindP[T any](arr []T, predict func(*T) bool) *T { } return nil } + +// FindIndex returns the index of the first element in the slice that satisfies the provided testing function. Otherwise -1 is returned. +func FindIndex[T any](arr []T, predict func(T) bool) int { + for i, v := range arr { + if predict(v) { + return i + } + } + return -1 +}