Search code examples
javascriptiteratorgeneratorimmutability

Why is this generator function wrapper consuming the iterator when I create a new generator each function call?


When reducing directly off of a freshly made Sequence can I reduce over the same seq multiple times, but if I try to repeatedly reduce off of the Sequence created from .map does it only work the first time?

It seems likely that I'm consuming the original iterator... but I don't see how/where. As far as I understand this code, Sequence::map builds a new generator to iterate on every time it is called, so it should be able to re-use the same seq every time. Can someone help me understand what I'm missing?

// A wrapper for a generatorFn
class Sequence {

  constructor(generatorFn) {
    if (typeof generatorFn === "function") {
      this[Symbol.iterator] = generatorFn;
    } else {
      throw new Error("Cannot create Sequence from provided argument");
    }
  }


  static of(obj) {
    //Create a generatorFn from an iterable object  
    function* genFn() {
        for (const x of obj) {
        yield x;
      }
    }
    return new Sequence(genFn);
  }

  map(fn) {
    //Make a generator from the generator function
    const gen = this[Symbol.iterator]();

    //Make a new generator function that applies fn to each value
    function* mapGenFn() {
      for (const x of gen) {
        yield fn(x);
      }
    }

    // Create a new sequence using the new generator function
    return new Sequence(mapGenFn);
  }

    reduce(fn, initial) {
    let acc;
    let first = true;
    // Make a new generator from the seq's generator fn
    const gen = this[Symbol.iterator]();
    if (initial) {
      acc = initial
      // iterate on the new generator
      for (const x of gen) {
        acc = fn(acc, x);
      }
    } else {
        acc = this.fold(fn);
    }
    return acc;
  }

  fold(fn) {
    const gen = this[Symbol.iterator]();
    let first = true;
    let acc;
    for (const x of gen) {
        if (first) {
            acc = x;
          first = false;
        } else {
          acc = fn(acc, x);
        }
    }
    return acc;
  }
}

const seqA = Sequence.of([1,2,3])
console.log("SeqA1 is: ", seqA.reduce((acc, x) => acc + x)); // 6
console.log("SeqA2 is: ", seqA.reduce((acc, x) => acc + x)); // 6
console.log("SeqA3 is: ", seqA.reduce((acc, x) => acc + x)); // 6

const seqB = Sequence.of([1,2,3]).map(x => x + 1);
console.log("SeqB1 is: ", seqB.reduce((acc, x) => acc + x)); // 9
console.log("SeqB2 is: ", seqB.reduce((acc, x) => acc + x)); // undefined
console.log("SeqB3 is: ", seqB.reduce((acc, x) => acc + x)); // undefined

A fiddle demonstrating the problem: https://jsfiddle.net/qsh9mupz/5/


Solution

  • The const gen = this[Symbol.iterator]() is not created every time you use the new sequence, but only once when you call .map(…). Move that part inside the mapGenFn:

    map(fn) {
      const gen = this[Symbol.iterator]; // no call here!
      return new Sequence(function* mapGenFn() {
        for (const x of gen()) {
    //                     ^^ create new iterator here every time the sequence uses mapGenFn
          yield fn(x);
        }
      });
    }