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 =;
    while (!result.done) {
      yield result.value;
      result =;
  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(; // 'state 1'
console.log(; // 'state 2'
Demonstrates using the cloned generator independently of the original.