map filter reduce

This commit is contained in:
xing 2022-09-24 22:14:47 +08:00
parent 993fa3809d
commit 8ba8e2c9b0
2 changed files with 74 additions and 2 deletions

View File

@ -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
}

View File

@ -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)
}
})
}
}