30秒学会 JavaScript 片段 · 2022年12月4日

30秒学会 JavaScript 片段 – Cycle generator

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 }

翻译自:https://www.30secondsofcode.org/js/s/cycle-generator