Last active
March 2, 2023 14:28
-
-
Save andyrudoff/01cfd3f388f40bedc7093481fa2204e1 to your computer and use it in GitHub Desktop.
javascript range() generator modeled after python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// range -- generator similar to python's range() | |
// | |
// range() will generate 0..MAX_SAFE_INTEGER | |
// range(end) will generate 0..(end-1) | |
// range(start, end) will generate start..(end-1) | |
// range(start, end, step) will step by step instead of 1 | |
// start can be larger than end if step is negative: | |
// for example range(10, 2, -1) | |
// | |
function* range(...args) { | |
let start = 0; | |
let end = Number.MAX_SAFE_INTEGER; | |
let step = 1; | |
if (args.length === 1) { | |
[end] = args; | |
} else if (args.length > 1) { | |
[start, end, step = 1] = args; | |
} | |
if (step > 0) { | |
// stepping up | |
while (start < end) { | |
yield start; | |
start += step; | |
} | |
} else { | |
// stepping down | |
while (start > end) { | |
yield start; | |
start += step; | |
} | |
} | |
} | |
// tests | |
for (x of range(5)) { | |
console.log(`range(5): ${x}`); | |
} | |
for (x of range(6, 10)) { | |
console.log(`range(6, 10): ${x}`); | |
} | |
for (x of range(10, 20, 3)) { | |
console.log(`range(10, 20, 3): ${x}`); | |
} | |
for (x of range(10, 2, -1)) { | |
console.log(`range(10, 2, -1): ${x}`); | |
} | |
for (x of range()) { | |
console.log(`range() until x > 5: ${x}`); | |
if (x > 5) { | |
break; | |
} | |
} | |
// why we use for...of instead of for...in. | |
// this generates the entire range into an array | |
// rather than letting it yield a value each iteration | |
for (x in [...range(5)]) { | |
console.log(`in range(5): ${x}`); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment