1
0
mirror of https://github.com/duke-git/lancet.git synced 2026-02-13 17:22:27 +08:00

feat: add FindLast func

This commit is contained in:
dudaodong
2022-01-24 15:28:47 +08:00
parent 8bb102cb6e
commit 1ad990ce9d
2 changed files with 43 additions and 1 deletions

View File

@@ -367,6 +367,34 @@ func Find(slice, function interface{}) (interface{}, bool) {
return sv.Index(index).Interface(), true
}
// FindLast iterates over elements of slice from end to begin, returning the first one that passes a truth test on function.
// The function signature should be func(index int, value interface{}) bool .
func FindLast(slice, function interface{}) (interface{}, bool) {
sv := sliceValue(slice)
fn := functionValue(function)
elemType := sv.Type().Elem()
if checkSliceCallbackFuncSignature(fn, elemType, reflect.ValueOf(true).Type()) {
panic("function param should be of type func(int, " + elemType.String() + ")" + reflect.ValueOf(true).Type().String())
}
index := -1
for i := sv.Len() - 1; i >= 0; i-- {
flag := fn.Call([]reflect.Value{reflect.ValueOf(i), sv.Index(i)})[0]
if flag.Bool() {
index = i
break
}
}
if index == -1 {
var none interface{}
return none, false
}
return sv.Index(index).Interface(), true
}
// FlattenDeep flattens slice recursive
func FlattenDeep(slice interface{}) interface{} {
sv := sliceValue(slice)