完善range

This commit is contained in:
xing 2022-09-24 22:55:39 +08:00
parent a8a7e73600
commit bdfc171dec
2 changed files with 50 additions and 2 deletions

View File

@ -30,10 +30,17 @@ func StructColumn[T any, M any](arr []M, field string) (r []T) {
} }
func RangeSlice[T ~int | ~uint | ~int64 | ~int8 | ~int16 | ~int32 | ~uint64](start, end, step T) []T { func RangeSlice[T ~int | ~uint | ~int64 | ~int8 | ~int16 | ~int32 | ~uint64](start, end, step T) []T {
r := make([]T, 0, int((end-start+1)/step+1)) l := int((end-start+1)/step + 1)
for i := start; i <= end; { if l < 0 {
l = 0 - l
}
r := make([]T, 0, l)
for i := start; ; {
r = append(r, i) r = append(r, i)
i = i + step i = i + step
if (step > 0 && i > end) || (step < 0 && i < end) {
break
}
} }
return r return r
} }
@ -199,3 +206,11 @@ func SliceReduce[T, R any](arr []T, fn func(T, R) R, r R) R {
} }
return r return r
} }
func SliceReverse[T any](arr []T) []T {
var r []T
for i := len(arr); i > 0; i-- {
r = append(r, arr[i-1])
}
return r
}

View File

@ -112,6 +112,15 @@ func TestRangeSlice(t *testing.T) {
}, },
want: []int{1, 4, 7, 10}, want: []int{1, 4, 7, 10},
}, },
{
name: "t4",
args: args{
start: 0,
end: -5,
step: -1,
},
want: []int{0, -1, -2, -3, -4, -5},
},
} }
for _, tt := range tests { for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) { t.Run(tt.name, func(t *testing.T) {
@ -411,3 +420,27 @@ func TestSliceMap(t *testing.T) {
}) })
} }
} }
func TestSliceReverse(t *testing.T) {
type args struct {
arr []int
}
tests := []struct {
name string
args args
want []int
}{
{
name: "t1",
args: args{arr: RangeSlice(1, 10, 1)},
want: RangeSlice(10, 1, -1),
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := SliceReverse(tt.args.arr); !reflect.DeepEqual(got, tt.want) {
t.Errorf("SliceReverse() = %v, want %v", got, tt.want)
}
})
}
}