diff --git a/helper/func.go b/helper/func.go index 043a196..2d36e0d 100644 --- a/helper/func.go +++ b/helper/func.go @@ -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 { - r := make([]T, 0, int((end-start+1)/step+1)) - for i := start; i <= end; { + l := int((end-start+1)/step + 1) + if l < 0 { + l = 0 - l + } + r := make([]T, 0, l) + for i := start; ; { r = append(r, i) i = i + step + if (step > 0 && i > end) || (step < 0 && i < end) { + break + } } return r } @@ -199,3 +206,11 @@ func SliceReduce[T, R any](arr []T, fn func(T, R) R, r R) 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 +} diff --git a/helper/func_test.go b/helper/func_test.go index c5f66a1..36694e1 100644 --- a/helper/func_test.go +++ b/helper/func_test.go @@ -112,6 +112,15 @@ func TestRangeSlice(t *testing.T) { }, 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 { 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) + } + }) + } +}