Cycle generator

JavaScript, Function, Generator · Oct 11, 2020

Creates a generator, looping over the given array indefinitely.

  • Use a non-terminating while loop, that will yield a value every time Generator.prototype.next() is called.
  • Use the module operator (%) with Array.prototype.length to get the next value's index and increment the counter after each yield statement.
const cycleGenerator = function* (arr) {
  let i = 0;
  while (true) {
    yield arr[i % arr.length];
    i++;
  }
};
const binaryCycle = cycleGenerator([0, 1]);
binaryCycle.next(); // { value: 0, done: false }
binaryCycle.next(); // { value: 1, done: false }
binaryCycle.next(); // { value: 0, done: false }
binaryCycle.next(); // { value: 1, 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 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

  • 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

  • Generate until condition is met

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

    JavaScript, Function · Jan 21, 2022