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

30秒学会 JavaScript 片段 – Repeat generator

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 }

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