Creates a generator, that generates all values in the given range using the given step.
while
loop to iterate from start
to end
, using yield
to return each value and then incrementing by step
.step
, to use a default value of 1
.const rangeGenerator = function* (start, end, step = 1) {
let i = start;
while (i < end) {
yield i;
i += step;
}
};
for (let i of rangeGenerator(6, 10)) console.log(i);
// Logs 6, 7, 8, 9
Snippet collection
JavaScript generator functions are a more advanced yet very powerful JavaScript ES6 feature, which you can start using in your code right now.
JavaScript, Date
Creates a generator, that generates all dates in the given range using the given step.
JavaScript, Function
Creates a generator, repeating the given value indefinitely.
JavaScript, Function
Creates a generator, that keeps producing new values until the given condition is met.