Repeat generator

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 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);; // { value: 5, done: false }; // { value: 5, done: false }; // { value: 4, done: false }; // { value: 4, done: false }

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.

More like this

  • JavaScript Generator Functions

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

    Collection · 17 snippets

  • Cycle generator

    Creates a generator, looping over the given array 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

  • Generate until condition is met

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

    JavaScript, Function · Jan 21, 2022