, döndüren bir metodu olan bir nesnedir. Bir nesne ise metodu varsa — bu, ve spread'in çalışmasını sağlayan şeydir. (), ile iteratörler oluşturmanın uygun bir yoludur.
, döndüren bir metodu olan bir nesnedir. Bir nesne ise metodu varsa — bu, ve spread'in çalışmasını sağlayan şeydir. (), ile iteratörler oluşturmanın uygun bir yoludur.
{ value, done }next()[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
Temel fikir: her yield noktasında yürütme duraklatılır ve sonraki .next() çağrısında devam ettirilir, çağrılar arasında yerel durumu korur. Talep edilene kadar hiçbir şey hesaplanmaz.
// 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
Generatörler, tembel/sonsuz dizileri, özel yinelemeyi ve bellek-verimli akışı sağlar.
Aynı zamanda erken async kütüphanelerinin (co) temeliydi ve async yinelemeyi (for await...of) destekler.
Iteratör protokolü, for...of, spread ve destructuring'i diziler, Maps, Sets ve stringler arasında birleştiren şeydir.
Junior'dan Senior'a detaylı cevaplarla bir BT mülakat soruları kütüphanesi.
Bağış Yap