Is there a function in JavaScript similar to Python\'s range()?
I think there should be a better way than to write the following lines every time:
Fusing together both answers from @Tadeck and @georg, I came up with this:
function* range(start, stop, step = 1) {
if (stop == null) {
// one param defined
stop = start;
start = 0;
}
for (let i = start; step > 0 ? i < stop : i > stop; i += step) {
yield i;
}
}
To use it in a for loop you need the ES6/JS1.7 for-of loop:
for (let i of range(5)) {
console.log(i);
}
// Outputs => 0 1 2 3 4
for (let i of range(0, 10, 2)) {
console.log(i);
}
// Outputs => 0 2 4 6 8
for (let i of range(10, 0, -2)) {
console.log(i);
}
// Outputs => 10 8 6 4 2