2025-01-27 13:19:52 +11:00
|
|
|
package moslice
|
|
|
|
|
|
|
|
|
|
func Contains[T comparable](ts []T, needle T) bool {
|
|
|
|
|
for _, t := range ts {
|
|
|
|
|
if t == needle {
|
|
|
|
|
return true
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
return false
|
|
|
|
|
}
|
|
|
|
|
|
2026-05-13 22:16:38 +10:00
|
|
|
func FirstWhere[T any](ts []T, predicate func(t T) bool) T {
|
|
|
|
|
var zeroT T
|
|
|
|
|
|
|
|
|
|
for _, t := range ts {
|
|
|
|
|
if predicate(t) {
|
|
|
|
|
return t
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
return zeroT
|
|
|
|
|
}
|
|
|
|
|
|
2026-09-05 09:40:33 +10:00
|
|
|
// FirstIndexWhere returns the index of the first element in the slice that satisfies the predicate. An empty slice will return -1
|
|
|
|
|
func FirstIndexWhere[T any](ts []T, predicate func(t T) bool) int {
|
|
|
|
|
for i, t := range ts {
|
|
|
|
|
if predicate(t) {
|
|
|
|
|
return i
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
return -1
|
|
|
|
|
}
|
|
|
|
|
|
2025-07-29 22:07:20 +10:00
|
|
|
func FindWhere[T any](ts []T, predicate func(t T) bool) (T, bool) {
|
2025-01-27 13:19:52 +11:00
|
|
|
var zeroT T
|
|
|
|
|
|
|
|
|
|
for _, t := range ts {
|
|
|
|
|
if predicate(t) {
|
|
|
|
|
return t, true
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
return zeroT, false
|
|
|
|
|
}
|
2025-06-19 13:23:00 +02:00
|
|
|
|
2025-07-29 22:07:20 +10:00
|
|
|
func FindWithIndexWhere[T any](ts []T, predicate func(t T) bool) (T, int, bool) {
|
2025-06-19 13:23:00 +02:00
|
|
|
var zeroT T
|
|
|
|
|
|
|
|
|
|
for i, t := range ts {
|
|
|
|
|
if predicate(t) {
|
|
|
|
|
return t, i, true
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
return zeroT, 0, false
|
|
|
|
|
}
|
2026-09-05 09:40:33 +10:00
|
|
|
|
|
|
|
|
// AnyWhere returns true if any element in the slice satisfies the predicate. An empty slice will return false
|
|
|
|
|
func AnyWhere[T any](ts []T, predicate func(t T) bool) bool {
|
|
|
|
|
for _, t := range ts {
|
|
|
|
|
if predicate(t) {
|
|
|
|
|
return true
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
return false
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// AllWhere returns true if all the element in the slice satisfies the predicate. An empty slice will return false
|
|
|
|
|
func AllWhere[T any](ts []T, predicate func(t T) bool) bool {
|
|
|
|
|
if len(ts) == 0 {
|
|
|
|
|
return false
|
|
|
|
|
}
|
|
|
|
|
for _, t := range ts {
|
|
|
|
|
if !predicate(t) {
|
|
|
|
|
return false
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
return true
|
|
|
|
|
}
|