Last active
January 26, 2019 06:15
-
-
Save kamoroso94/741ade05690e846b544293c1da57ae67 to your computer and use it in GitHub Desktop.
A simple range generator in JavaScript for iterating through a left-closed, right-open interval
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
function* range(start, end, step) { | |
if(end === undefined) { | |
end = start; | |
start = 0; | |
} | |
if(step === 0) throw new RangeError('step must be non-zero'); | |
if(step === undefined) step = Math.sign(end - start); | |
const dir = Math.sign(step); | |
if(Math.sign(end - start) != dir) { | |
const temp = start; | |
start = end; | |
end = temp; | |
} | |
for(let i = start; Math.sign(end - i) == dir; i += step) { | |
yield i; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
More examples:
Console output: