902 B
902 B
title, tags, author, cover, firstSeen
| title | tags | author | cover | firstSeen |
|---|---|---|---|---|
| Generate until condition is met | function,generator | chalarangelo | blog_images/type-stamps.jpg | 2022-01-21T05:00:00-04:00 |
Creates a generator, that keeps producing new values until the given condition is met.
- Initialize the current
valusing theseedvalue. - Use a
whileloop to iterate while theconditionfunction called with the currentvalreturnsfalse. - Use
yieldto return the currentvaland optionally receive a new seed value,nextSeed. - Use the
nextfunction to calculate the next value from the currentvaland thenextSeed.
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]