Generator Functions — function ที่ pause ได้
Generator function ใช้ function* และ yield เพื่อส่งค่าออกทีละตัวโดยไม่ต้องสร้าง array ทั้งหมด
function* range(start, end, step = 1) {
for (let i = start; i < end; i += step) {
yield i;
}
}
for (const n of range(0, 1_000_000)) {
if (n > 5) break; // หยุดได้เลย — ไม่ต้องสร้าง array 1 ล้านตัว
}
Infinite sequence:
function* fibonacci() {
let [a, b] = [0, 1];
while (true) {
yield a;
[a, b] = [b, a + b];
}
}
const fib = fibonacci();
fib.next().value; // 0
fib.next().value; // 1
fib.next().value; // 1
Lazy pipeline — ประหยัด memory:
function* map(iter, fn) { for (const x of iter) yield fn(x); }
function* filter(iter, pred) { for (const x of iter) if (pred(x)) yield x; }
function* take(iter, n) { for (const x of iter) { yield x; if (--n === 0) return; } }
const result = [...take(filter(map(range(0, 1e6), x => x * 2), x => x % 6 === 0), 5)];
// [0, 6, 12, 18, 24] — ประมวลผลแค่เท่าที่ต้องการ
Async generator (async function* + for await...of) ใช้สำหรับ stream data