1
0
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:
dudaodong
2023-03-06 17:49:56 +08:00
parent 6a9eb645bb
commit 28d0428b50
3 changed files with 49 additions and 0 deletions

View File

@@ -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
}

View File

@@ -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]
}

View File

@@ -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)
}