একটি একটি object যা method রাখে যা প্রদান করে। একটি object যদি এটির method থাকে — এটিই যা এবং spread কে কাজ করে। একটি () iterators তৈরি করার একটি সুবিধাজনক উপায় যা এর সাথে করতে পারে।
একটি একটি object যা method রাখে যা প্রদান করে। একটি object যদি এটির method থাকে — এটিই যা এবং spread কে কাজ করে। একটি () iterators তৈরি করার একটি সুবিধাজনক উপায় যা এর সাথে করতে পারে।
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 এ suspend হয় এবং পরবর্তী .next() এ resumes হয়, calls এর মধ্যে local state সংরক্ষণ করে। আপনি এটি চেয়ে না হওয়া পর্যন্ত কিছুই computed হয় না।
// 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
Generators lazy/infinite sequences, custom iteration, এবং memory-efficient streaming সক্ষম করে।
তারা প্রাথমিক async libraries (co) এর ভিত্তিও ছিল এবং async iteration (for await...of) কে সমর্থন করে।
Iterator protocol হল যা for...of, spread, এবং destructuring কে arrays, Maps, Sets, এবং strings এর মধ্যে একীভূত করে।