mirror of
https://github.com/duke-git/lancet.git
synced 2025-11-02 19:44:00 +08:00
feat: add RangeWithStep function
This commit is contained in:
@@ -200,3 +200,19 @@ func Range[T constraints.Integer | constraints.Float](start T, count int) []T {
|
|||||||
|
|
||||||
return result
|
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
|
||||||
|
}
|
||||||
|
|||||||
@@ -203,3 +203,21 @@ func ExampleRange() {
|
|||||||
// [-4 -3 -2 -1]
|
// [-4 -3 -2 -1]
|
||||||
// [1 2 3 4]
|
// [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]
|
||||||
|
}
|
||||||
|
|||||||
@@ -145,9 +145,25 @@ func TestRange(t *testing.T) {
|
|||||||
result2 := Range(1, -4)
|
result2 := Range(1, -4)
|
||||||
result3 := Range(-4, 4)
|
result3 := Range(-4, 4)
|
||||||
result4 := Range(1.0, 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}, result1)
|
||||||
assert.Equal([]int{1, 2, 3, 4}, result2)
|
assert.Equal([]int{1, 2, 3, 4}, result2)
|
||||||
assert.Equal([]int{-4, -3, -2, -1}, result3)
|
assert.Equal([]int{-4, -3, -2, -1}, result3)
|
||||||
assert.Equal([]float64{1.0, 2.0, 3.0, 4.0}, result4)
|
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)
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user