Generators

Symbol.iterator property

function*gen() { /\*some code \*/}
var g = gen();
g[Symbol.iterator]() === g // true

gen is a Generator function, calling it will generate a traverser object g. Its Symbol.iterator property, which is also an iterator object generation function, returns itself after execution

Relationship with Iterator interface

var gen = {};
gen[Symbol.iterator] = function*() {
  yield 1;
  yield 2;
  yield 3;
};
[...gen] // => [1, 2, 3]

The Generator function is assigned to the Symbol.iterator property, so that the gen object has the Iterator interface, which can be traversed by the ... operator

For..of + iterator

let fibonacci = {
  [Symbol.iterator]() {
    let pre = 0, cur = 1;
    return {
      next() {
        [pre, cur] = [cur, pre + cur];
return { done: false, value: cur }
      }
    }
  }
}
for (var n of fibonacci) {
  // truncate sequence at 1000
  if (n > 1000) break;
  console.log(n);
}

For iterating over generators and arrays. See: For..of iteration

Generator function

function*idMaker () {
  let id = 0
  while (true) { yield id++ }
}

let gen = idMaker()
gen.next().value // → 0
gen.next().value // → 1
gen.next().value // → 2

it's complicated. See: Generators

Comments