Repeat generator

Angelos Chalaris · JavaScript, Function, Generator · Oct 11, 2020

Creates a generator, repeating the given value indefinitely.

  • Use a non-terminating while loop, that will yield a value every time Generator.prototype.next() is called.
  • Use the return value of the yield statement to update the returned value if the passed value is not undefined.
const repeatGenerator = function* (val) {
  let v = val;
  while (true) {
    let newV = yield v;
    if (newV !== undefined) v = newV;
  }
};
const repeater = repeatGenerator(5);
repeater.next(); // { value: 5, done: false }
repeater.next(); // { value: 5, done: false }
repeater.next(4); // { value: 4, done: false }
repeater.next(); // { value: 4, done: false }

Recommended snippets & collections

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

  • Cycle generator

    JavaScript, Function

    Creates a generator, looping over the given array indefinitely.

  • Range generator

    JavaScript, Function

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

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