Skip to content
This repository was archived by the owner on Nov 8, 2024. It is now read-only.

Commit ff0a398

Browse files
committed
Refactor range with step
1 parent 5f60ba9 commit ff0a398

File tree

1 file changed

+12
-14
lines changed

1 file changed

+12
-14
lines changed

range.go

Lines changed: 12 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -22,24 +22,22 @@ func Range[Int intType](start Int, stop Int) func(func(Int) bool) {
2222
// step is 0 then no iteration will take place.
2323
func RangeWithStep[Int intType](start Int, stop Int, step Int) func(func(Int) bool) {
2424
return func(yield func(Int) bool) {
25-
if step > 0 {
26-
for i := uint64(start); i < uint64(stop); i += uint64(step) {
27-
if !yield(Int(i)) {
28-
return
29-
}
30-
}
25+
if step == 0 {
26+
return
3127
}
3228

33-
if step < 0 {
34-
for i := uint64(start); i > uint64(stop); i += uint64(step) {
35-
if !yield(Int(i)) {
36-
return
37-
}
38-
}
29+
delta := int64(stop) - int64(start)
30+
steps := int64(delta) / int64(step)
31+
rem := int64(delta) % int64(step)
32+
if rem > 0 {
33+
steps += 1
3934
}
4035

41-
if step == 0 {
42-
return
36+
for i := int64(0); i < steps; i++ {
37+
num := i*int64(step) + int64(start)
38+
if !yield(Int(num)) {
39+
return
40+
}
4341
}
4442
}
4543
}

0 commit comments

Comments
 (0)