એક એક object છે જેમાં method છે જે આપે છે. એક object છે જો તેમાં method હોય — આજ વસ્તુ છે જે અને spread કામ કરે છે. એક () એ ઇટરેટર્સ બનાવવાનો સુવિધાજનક રીત છે જે વડે કરી શકે.
એક એક object છે જેમાં method છે જે આપે છે. એક object છે જો તેમાં method હોય — આજ વસ્તુ છે જે અને spread કામ કરે છે. એક () એ ઇટરેટર્સ બનાવવાનો સુવિધાજનક રીત છે જે વડે કરી શકે.
next(){ value, done }[Symbol.iterator]for...offunction*yieldfunction* 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
મુખ્ય વિચાર: execution દરેક yield પર અટકે છે અને આગલા .next() પર ફરીથી શરૂ થાય છે, કૉલ્સ વચ્ચે local state સાચવે છે. જ્યાં સુધી તમે માગો ત્યાં સુધી કંઈ compute થતું નથી.
// 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
જનરેટર્સ આલસી/અનંત સિક્વન્સ, કસ્ટમ ઇટરેશન, અને મેમોરી-કુશળ streaming સક્ષમ કરે છે.
તેઓ પ્રાથમિક async libraries (co) નો પણ આધાર હતા અને async ઇટરેશન (for await...of) ને આધાર આપે છે.
ઇટરેટર protocol એ છે જે arrays, Maps, Sets, અને strings માટે for...of, spread, અને destructuring એક કરે છે.