select.go (555B)
1 package slices 2 3 // SelectFirst finds a item from beginning of slice and returns the first 4 // matched item. 5 func SelectFirst[T any](items []T, action func(T) bool) (result T, ok bool) { 6 for _, item := range items { 7 if action(item) { 8 return item, true 9 } 10 } 11 return 12 } 13 14 // SelectLast finds a item from ending of slice and returns the first 15 // matched item. 16 func SelectLast[T any](items []T, action func(T) bool) (result T, ok bool) { 17 for i := len(items) - 1; i >= 0; i-- { 18 item := items[i] 19 if action(item) { 20 return item, true 21 } 22 } 23 return 24 }