39 lines
657 B
Go
39 lines
657 B
Go
package slices
|
|
|
|
func Filter[T any](slice []T, f func(T) bool) []T {
|
|
ret := make([]T, 0, len(slice))
|
|
for _, v := range slice {
|
|
if f(v) {
|
|
ret = append(ret, v)
|
|
}
|
|
}
|
|
return ret
|
|
}
|
|
|
|
func FindFirst[T any](slice []T, f func(T) bool) (T, bool) {
|
|
for _, v := range slice {
|
|
if f(v) {
|
|
return v, true
|
|
}
|
|
}
|
|
return *new(T), false
|
|
}
|
|
|
|
func FindFirstIndex[T any](slice []T, f func(T) bool) (int, bool) {
|
|
for i, v := range slice {
|
|
if f(v) {
|
|
return i, true
|
|
}
|
|
}
|
|
return -1, false
|
|
}
|
|
|
|
func FindLastIndex[T any](slice []T, f func(T) bool) (int, bool) {
|
|
for i := len(slice); i >= 0; i-- {
|
|
if f(slice[i]) {
|
|
return i, true
|
|
}
|
|
}
|
|
return -1, false
|
|
}
|