Blog>
Snippets

Deep Cloning Generator State

Illustrates techniques for deep cloning the internal state of a generator object to avoid shared state pitfalls, focusing on scenarios where shallow cloning is insufficient.
function* originalGenerator() {
  yield 'state 1';
  yield 'state 2';
}
Defines the original generator function.
function deepCloneGenerator(genFunc) {
  const history = [];
  const clone = (function* () {
    for (const state of history) {
      yield state;
    }
    let result = genFunc.next();
    while (!result.done) {
      history.push(result.value);
      yield result.value;
      result = genFunc.next();
    }
  })();
  return clone;
}
Creates a deep clone of a generator. It replays past yielded values and continues yielding new values.
const original = originalGenerator();
const clone = deepCloneGenerator(original);
Generates instances of the original generator and its deep clone.
console.log(clone.next().value); // 'state 1'
console.log(clone.next().value); // 'state 2'
Demonstrates using the cloned generator independently of the original.