Creates a generator, that keeps producing new values until the given condition is met.
val
using the seed
value.while
loop to iterate while the condition
function called with the current val
returns false
.yield
to return the current val
and optionally receive a new seed value, nextSeed
.next
function to calculate the next value from the current val
and the nextSeed
.const generateUntil = function* (seed, condition, next) {
let val = seed;
let nextSeed = null;
while (!condition(val)) {
nextSeed = yield val;
val = next(val, nextSeed);
}
return val;
};
[...generateUntil(1, v => v > 5, v => ++v)]; // [1, 2, 3, 4, 5]
Would you like to help us improve 30 seconds of code?Take a quick survey
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, Function
Creates a generator, that keeps producing new values as long as the given condition is met.
JavaScript, Function
Creates a generator, repeating the given value indefinitely.
JavaScript, Function
Creates a generator, that generates all values in the given range using the given step.