Un è un object con un metodo che restituisce . Un object è se ha un metodo — è quello che rende e spread funzionanti. Un () è un modo conveniente per creare iterators che possono con .
Un è un object con un metodo che restituisce . Un object è se ha un metodo — è quello che rende e spread funzionanti. Un () è un modo conveniente per creare iterators che possono con .
next(){ value, done }[Symbol.iterator]for...offunction*yieldI generators producono valori pigramente
function* idGenerator() {
let id = 1;
while (true) { // infinite, but lazy — only computes on demand
yield id++; // pause here, return a value, resume on next()
}
}
const gen = idGenerator();
gen.next().value; // 1
gen.next().value; // 2 — execution resumed where it paused
L'idea chiave: l'esecuzione si sospende ad ogni yield e riprende al prossimo .next(), preservando lo stato locale tra le chiamate. Nulla viene calcolato finché non lo chiedi.
// process a huge/infinite sequence without building it all in memory
function* take(iterable, n) {
let i = 0;
for (const x of iterable) {
if (i++ >= n) return;
yield x;
}
}
[...take(idGenerator(), 3)]; // [1, 2, 3] — from an infinite generator
const range = {
from: 1, to: 3,
*[Symbol.iterator]() { for (let i = this.from; i <= this.to; i++) yield i; },
};
[...range]; // [1, 2, 3] — works with for...of and spread
I generators consentono sequenze pigre/infinite, iterazione personalizzata e streaming efficiente in memoria.
Sono stati anche la base delle prime librerie async (co) e sottendono l'iterazione async (for await...of).
Il protocollo iterator è ciò che unifica for...of, spread e destructuring su arrays, Maps, Sets e stringhe.