Generate while condition is met
JavaScript, Function, Generator · Jan 21, 2022

Creates a generator, that keeps producing new values as long as the given condition is met.
- Initialize the current
val
using theseed
value. - Use a
while
loop to iterate while thecondition
function called with the currentval
returnstrue
. - Use
yield
to return the currentval
and optionally receive a new seed value,nextSeed
. - Use the
next
function to calculate the next value from the currentval
and thenextSeed
.
const generateWhile = function* (seed, condition, next) {
let val = seed;
let nextSeed = null;
while (condition(val)) {
nextSeed = yield val;
val = next(val, nextSeed);
}
return val;
};
[...generateWhile(1, v => v <= 5, v => ++v)]; // [1, 2, 3, 4, 5]