Skip to content

Instantly share code, notes, and snippets.

@kamoroso94
Last active January 26, 2019 06:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kamoroso94/741ade05690e846b544293c1da57ae67 to your computer and use it in GitHub Desktop.
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
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;
}
}
@kamoroso94
Copy link
Author

kamoroso94 commented Feb 21, 2017

Example usage:

for(const i of range(10)) {
    console.log(i);
}

Console output:

0
1
2
3
4
5
6
7
8
9

@kamoroso94
Copy link
Author

More examples:

for(const x of range(5, 0)) {
  console.log(x);
}

Console output:

5
4
3
2
1

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment