Skip to content

Commit

Permalink
mr: add FindIndex function
Browse files Browse the repository at this point in the history
  • Loading branch information
ImSingee committed Aug 29, 2023
1 parent 36dd2b6 commit c48c9b1
Showing 1 changed file with 12 additions and 0 deletions.
12 changes: 12 additions & 0 deletions mr/search.go
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand All @@ -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) {
Expand All @@ -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
}

0 comments on commit c48c9b1

Please sign in to comment.