feat: narr 添加一些聚合(高阶)方法。

main v1.1.11
NoahLan 7 months ago
parent 2f4f631390
commit 837d1fcd7f

@ -425,3 +425,54 @@ func Map[T any, V any](list []T, mapFn func(obj T) (val V, find bool)) []V {
func Column[T any, V any](list []T, mapFn func(obj T) (val V, find bool)) []V {
return Map(list, mapFn)
}
// Every check all true in given slice
func Every[T any](list []T, fn func(T) bool) bool {
if len(list) == 0 {
return false
}
for _, t := range list {
if !fn(t) {
return false
}
}
return true
}
// Some check some true in given slice
func Some[T any](list []T, fn func(T) bool) bool {
if len(list) == 0 {
return false
}
for _, t := range list {
if fn(t) {
return true
}
}
return false
}
// Filter returns a new slice by given filter func
func Filter[T any](list []T, filterFn func(i int, currentValue T) bool) []T {
ret := make([]T, 0)
if list == nil {
return ret
}
for i, v := range list {
if filterFn(i, v) {
ret = append(ret, v)
}
}
return ret
}
// Reduce all list item by given func
func Reduce[T any, M any](list []T, reduceFn func(total M, currentVal T, idx int) M, initialValue M) M {
ret := initialValue
for i, item := range list {
ret = reduceFn(ret, item, i)
}
return ret
}

Loading…
Cancel
Save