From 51a6912eb37e6d876128ba6cc040a20e3631d451 Mon Sep 17 00:00:00 2001 From: dudaodong Date: Mon, 6 Mar 2023 18:05:58 +0800 Subject: [PATCH] feat: add RangeWithStep function --- mathutil/mathutil.go | 16 ++++++++++++++++ mathutil/mathutil_exmaple_test.go | 18 ++++++++++++++++++ mathutil/mathutil_test.go | 16 ++++++++++++++++ 3 files changed, 50 insertions(+) diff --git a/mathutil/mathutil.go b/mathutil/mathutil.go index 0390b16..a1474b3 100644 --- a/mathutil/mathutil.go +++ b/mathutil/mathutil.go @@ -200,3 +200,19 @@ func Range[T constraints.Integer | constraints.Float](start T, count int) []T { return result } + +// RangeWithStep creates a slice of numbers from start to end with specified step. +// Play: todo +func RangeWithStep[T constraints.Integer | constraints.Float](start, end, step T) []T { + result := []T{} + + if start >= end || step == 0 { + return result + } + + for i := start; i < end; i += step { + result = append(result, i) + } + + return result +} diff --git a/mathutil/mathutil_exmaple_test.go b/mathutil/mathutil_exmaple_test.go index 1e78be6..0e78e34 100644 --- a/mathutil/mathutil_exmaple_test.go +++ b/mathutil/mathutil_exmaple_test.go @@ -203,3 +203,21 @@ func ExampleRange() { // [-4 -3 -2 -1] // [1 2 3 4] } + +func ExampleRangeWithStep() { + result1 := RangeWithStep(1, 4, 1) + result2 := RangeWithStep(1, -1, 0) + result3 := RangeWithStep(-4, 1, 2) + result4 := RangeWithStep(1.0, 4.0, 1.1) + + fmt.Println(result1) + fmt.Println(result2) + fmt.Println(result3) + fmt.Println(result4) + + // Output: + // [1 2 3] + // [] + // [-4 -2 0] + // [1 2.1 3.2] +} diff --git a/mathutil/mathutil_test.go b/mathutil/mathutil_test.go index 8c99a88..8adcc93 100644 --- a/mathutil/mathutil_test.go +++ b/mathutil/mathutil_test.go @@ -145,9 +145,25 @@ func TestRange(t *testing.T) { result2 := Range(1, -4) result3 := Range(-4, 4) result4 := Range(1.0, 4) + result5 := Range(1, 0) assert.Equal([]int{1, 2, 3, 4}, result1) assert.Equal([]int{1, 2, 3, 4}, result2) assert.Equal([]int{-4, -3, -2, -1}, result3) assert.Equal([]float64{1.0, 2.0, 3.0, 4.0}, result4) + assert.Equal([]int{}, result5) +} + +func TestRangeWithStep(t *testing.T) { + assert := internal.NewAssert(t, "Range") + + result1 := RangeWithStep(1, 4, 1) + result2 := RangeWithStep(1, -1, 0) + result3 := RangeWithStep(-4, 1, 2) + result4 := RangeWithStep(1.0, 4.0, 1.1) + + assert.Equal([]int{1, 2, 3}, result1) + assert.Equal([]int{}, result2) + assert.Equal([]int{-4, -2, 0}, result3) + assert.Equal([]float64{1.0, 2.1, 3.2}, result4) }