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 the seed value.
  • Use a while loop to iterate while the condition function called with the current val returns true.
  • Use yield to return the current val and optionally receive a new seed value, nextSeed.
  • Use the next function to calculate the next value from the current val and the nextSeed.
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]

Written by Angelos Chalaris

I'm Angelos Chalaris, a JavaScript software engineer, based in Athens, Greece. The best snippets from my coding adventures are published here to help others learn to code.

If you want to keep in touch, follow me on GitHub or Twitter.

More like this

  • JavaScript Generator Functions

    JavaScript generator functions are a more advanced yet very powerful JavaScript ES6 feature, which you can start using in your code right now.

    Collection · 17 snippets

  • Generate until condition is met

    Creates a generator, that keeps producing new values until the given condition is met.

    JavaScript, Function · Jan 21, 2022

  • Repeat generator

    Creates a generator, repeating the given value indefinitely.

    JavaScript, Function · Oct 11, 2020

  • Range generator

    Creates a generator, that generates all values in the given range using the given step.

    JavaScript, Function · Oct 11, 2020