github.com/isyscore/isc-gobase@v1.5.3-0.20231218061332-cbc7451899e9/isc/find.go (about) 1 package isc 2 3 import "reflect" 4 5 func Find[T any](list []T, f func(T) bool) *T { 6 var n *T = nil 7 for _, e := range list { 8 if f(e) { 9 n = &e 10 break 11 } 12 } 13 return n 14 } 15 16 func FindLast[T any](list []T, f func(T) bool) *T { 17 var n *T = nil 18 for i := len(list) - 1; i >= 0; i-- { 19 e := list[i] 20 if f(e) { 21 n = &e 22 break 23 } 24 } 25 return n 26 } 27 28 func First[T any](list []T) T { 29 return list[0] 30 } 31 32 func Last[T any](list []T) T { 33 return list[len(list)-1] 34 } 35 36 func FirstOrNull[T any](list []T) *T { 37 var n *T = nil 38 if len(list) > 0 { 39 n = &list[0] 40 } 41 return n 42 } 43 44 func LastOrNull[T any](list []T) *T { 45 var n *T = nil 46 if len(list) > 0 { 47 n = &list[len(list)-1] 48 } 49 return n 50 } 51 52 //IndexOf 判断元素item是否在分片中,示例res := IndexOf[int](list,item),使用时须指明类型 53 func IndexOf[T any](list []T, item T) int { 54 idx := -1 55 for i, e := range list { 56 if reflect.DeepEqual(e, item) { 57 idx = i 58 break 59 } 60 } 61 return idx 62 } 63 64 func LastIndexOf[T any](list []T, item T) int { 65 idx := -1 66 for i := len(list) - 1; i >= 0; i-- { 67 e := list[i] 68 if reflect.DeepEqual(e, item) { 69 idx = i 70 break 71 } 72 } 73 return idx 74 } 75 76 func IndexOfCondition[T any](list []T, f func(T) bool) int { 77 idx := -1 78 for i, e := range list { 79 if f(e) { 80 idx = i 81 break 82 } 83 } 84 return idx 85 } 86 87 func LastIndexOfCondition[T any](list []T, f func(T) bool) int { 88 idx := -1 89 for i := len(list) - 1; i >= 0; i-- { 90 e := list[i] 91 if f(e) { 92 idx = i 93 break 94 } 95 } 96 return idx 97 }