Skip to content

Commit

Permalink
#30. Fix step > 1 + readme
Browse files Browse the repository at this point in the history
  • Loading branch information
arthurkushman committed Apr 28, 2019
2 parents 435d21a + bd6e41a commit 3d288f4
Show file tree
Hide file tree
Showing 3 changed files with 38 additions and 4 deletions.
3 changes: 2 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -236,6 +236,7 @@ creates an int slice of min to max range
```go
pgo.Range(3, 9) // []int{3, 4, 5, 6, 7, 8, 9}

pgo.Range(-3, 7) // []int{-3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7}
// If a step value is given, it will be used as the increment between elements in the sequence.
pgo.Range(-3, 7, 5) // []int{-3, 2, 7}
```
See more examples in *_test.go files.
19 changes: 16 additions & 3 deletions array.go
Original file line number Diff line number Diff line change
Expand Up @@ -218,11 +218,24 @@ func ArrayIntersect(arrays ...interface{}) []interface{} {
return result
}

// Range creates an int slice of min to max range
func Range(min, max int) []int {
// Range creates int slice of min to max range
// If a step value is given, it will be used as the increment between elements in the sequence.
// step should be given as a positive number.
// If not specified, step will default to 1.
func Range(min, max int, step ...interface{}) []int {
var slice []int

for i := min; i <= max; i++ {
var argsLen = len(step)

var stepp = 1
if argsLen > 0 && step[0] != nil {
st, ok := step[0].(int)
if !ok || st > 1 {
stepp = st
}
}

for i := min; i <= max; i += stepp {
slice = append(slice, i)
}

Expand Down
20 changes: 20 additions & 0 deletions array_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -287,6 +287,16 @@ var testRange = []struct {
{-3, 7, []int{-3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7}},
}

var testRangeWithStep = []struct {
min int
max int
step int
result []int
}{
{3, 9, 2, []int{3, 5, 7, 9}},
{-3, 7, 5, []int{-3, 2, 7}},
}

func TestRange(t *testing.T) {
for _, object := range testRange {

Expand All @@ -297,4 +307,14 @@ func TestRange(t *testing.T) {
}
}
}

for _, object := range testRangeWithStep {

res := pgo.Range(object.min, object.max, object.step)
for k, v := range res {
if v != object.result[k] {
t.Fatalf("want %v, got %v", object.result[k], v)
}
}
}
}

0 comments on commit 3d288f4

Please sign in to comment.