feat: narr collection 高阶方法添加索引。

main v1.1.12
NoahLan 6 months ago
parent 837d1fcd7f
commit b01002828e

@ -410,11 +410,11 @@ func ExceptWhile(data any, fn Predicate) any {
// Map a list to new list
//
// eg: mapping [object0{},object1{},...] to flatten list [object0.someKey, object1.someKey, ...]
func Map[T any, V any](list []T, mapFn func(obj T) (val V, find bool)) []V {
func Map[T any, V any](list []T, mapFn func(idx int, obj T) (val V, find bool)) []V {
flatArr := make([]V, 0, len(list))
for _, obj := range list {
if target, ok := mapFn(obj); ok {
for i, obj := range list {
if target, ok := mapFn(i, obj); ok {
flatArr = append(flatArr, target)
}
}
@ -422,17 +422,17 @@ func Map[T any, V any](list []T, mapFn func(obj T) (val V, find bool)) []V {
}
// Column alias of Map func
func Column[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(idx int, 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 {
func Every[T any](list []T, fn func(idx int, v T) bool) bool {
if len(list) == 0 {
return false
}
for _, t := range list {
if !fn(t) {
for i, t := range list {
if !fn(i, t) {
return false
}
}
@ -440,12 +440,12 @@ func Every[T any](list []T, fn func(T) bool) bool {
}
// Some check some true in given slice
func Some[T any](list []T, fn func(T) bool) bool {
func Some[T any](list []T, fn func(idx int, v T) bool) bool {
if len(list) == 0 {
return false
}
for _, t := range list {
if fn(t) {
for i, t := range list {
if fn(i, t) {
return true
}
}
@ -453,7 +453,7 @@ func Some[T any](list []T, fn func(T) bool) bool {
}
// Filter returns a new slice by given filter func
func Filter[T any](list []T, filterFn func(i int, currentValue T) bool) []T {
func Filter[T any](list []T, filterFn func(idx int, v T) bool) []T {
ret := make([]T, 0)
if list == nil {
return ret
@ -469,7 +469,7 @@ func Filter[T any](list []T, filterFn func(i int, currentValue T) bool) []T {
}
// 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 {
func Reduce[T any, M any](list []T, reduceFn func(sum M, v T, idx int) M, initialValue M) M {
ret := initialValue
for i, item := range list {
ret = reduceFn(ret, item, i)

@ -306,7 +306,7 @@ func TestMap(t *testing.T) {
{"name": "john", "age": 34},
}
flatArr := narr.Column(list1, func(obj map[string]any) (val any, find bool) {
flatArr := narr.Column(list1, func(idx int, obj map[string]any) (val any, find bool) {
return obj["age"], true
})

Loading…
Cancel
Save