mirror of
https://github.com/duke-git/lancet.git
synced 2026-02-04 12:52:28 +08:00
feat: add Range function
This commit is contained in:
@@ -183,3 +183,20 @@ func Average[T constraints.Integer | constraints.Float](numbers ...T) T {
|
||||
}
|
||||
return sum / n
|
||||
}
|
||||
|
||||
// Range creates a slice of numbers from start with specified count, element step is 1.
|
||||
// Play: todo
|
||||
func Range[T constraints.Integer | constraints.Float](start T, count int) []T {
|
||||
size := count
|
||||
if count < 0 {
|
||||
size = -count
|
||||
}
|
||||
|
||||
result := make([]T, size)
|
||||
|
||||
for i, j := 0, start; i < size; i, j = i+1, j+1 {
|
||||
result[i] = j
|
||||
}
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
@@ -185,3 +185,21 @@ func ExampleMinBy() {
|
||||
// ab
|
||||
//
|
||||
}
|
||||
|
||||
func ExampleRange() {
|
||||
result1 := Range(1, 4)
|
||||
result2 := Range(1, -4)
|
||||
result3 := Range(-4, 4)
|
||||
result4 := Range(1.0, 4)
|
||||
|
||||
fmt.Println(result1)
|
||||
fmt.Println(result2)
|
||||
fmt.Println(result3)
|
||||
fmt.Println(result4)
|
||||
|
||||
// Output:
|
||||
// [1 2 3 4]
|
||||
// [1 2 3 4]
|
||||
// [-4 -3 -2 -1]
|
||||
// [1 2 3 4]
|
||||
}
|
||||
|
||||
@@ -137,3 +137,17 @@ func TestMinBy(t *testing.T) {
|
||||
})
|
||||
assert.Equal("", res3)
|
||||
}
|
||||
|
||||
func TestRange(t *testing.T) {
|
||||
assert := internal.NewAssert(t, "Range")
|
||||
|
||||
result1 := Range(1, 4)
|
||||
result2 := Range(1, -4)
|
||||
result3 := Range(-4, 4)
|
||||
result4 := Range(1.0, 4)
|
||||
|
||||
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)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user