diff --git a/helper/func.go b/helper/func.go index 6d9bac5..043a196 100644 --- a/helper/func.go +++ b/helper/func.go @@ -175,10 +175,27 @@ func ClearClosedTag(s []string) []string { } } -func SliceMap[T any, R any](arr []T, fun func(T) R) []R { +func SliceMap[T, R any](arr []T, fn func(T) R) []R { r := make([]R, 0, len(arr)) for _, t := range arr { - r = append(r, fun(t)) + r = append(r, fn(t)) + } + return r +} + +func SliceFilter[T any](arr []T, fn func(T) bool) []T { + var r []T + for _, t := range arr { + if fn(t) { + r = append(r, t) + } + } + return r +} + +func SliceReduce[T, R any](arr []T, fn func(T, R) R, r R) R { + for _, t := range arr { + r = fn(t, r) } return r } diff --git a/helper/func_test.go b/helper/func_test.go index ae98861..ea211f6 100644 --- a/helper/func_test.go +++ b/helper/func_test.go @@ -326,3 +326,58 @@ func Test_clearTag(t *testing.T) { }) } } + +func TestSliceReduce(t *testing.T) { + type args struct { + arr []int + fn func(int, int) int + r int + } + tests := []struct { + name string + args args + want int + }{ + { + name: "t1", + args: args{arr: RangeSlice(1, 10, 1), fn: func(i int, i2 int) int { + return i + i2 + }}, + want: 55, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := SliceReduce(tt.args.arr, tt.args.fn, tt.args.r); !reflect.DeepEqual(got, tt.want) { + t.Errorf("SliceReduce() = %v, want %v", got, tt.want) + } + }) + } +} + +func TestSliceFilter(t *testing.T) { + type args struct { + arr []int + fn func(int) bool + } + tests := []struct { + name string + args args + want []int + }{ + { + name: "t1", + args: args{arr: RangeSlice(1, 10, 1), fn: func(i int) bool { + return i > 4 + }}, + want: RangeSlice(5, 10, 1), + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := SliceFilter(tt.args.arr, tt.args.fn); !reflect.DeepEqual(got, tt.want) { + t.Errorf("SliceFilter() = %v, want %v", got, tt.want) + } + }) + } +}