Learn
← Previous Next →

Hari 14: Iterators & Generators

55 min Last updated 09 Apr 2026

Iterator Protocol

// Objek iterable mengimplementasikan [Symbol.iterator]
const range = {
    from: 1,
    to: 5,
    [Symbol.iterator]() {
        let current = this.from;
        const last = this.to;
        return {
            next() {
                return current <= last
                    ? { value: current++, done: false }
                    : { value: undefined, done: true };
            }
        };
    }
};

for (const n of range) process.stdout.write(n + " ");
// 1 2 3 4 5
console.log([...range]); // [1, 2, 3, 4, 5]

Generator Function

function* fibonacci() {
    let [a, b] = [0, 1];
    while (true) {
        yield a;
        [a, b] = [b, a + b];
    }
}

const fib = fibonacci();
const sepuluhFib = Array.from({ length: 10 }, () => fib.next().value);
console.log(sepuluhFib); // [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]

// Generator sebagai range
function* range(start, end, step = 1) {
    for (let i = start; i <= end; i += step) yield i;
}
console.log([...range(0, 10, 2)]); // [0, 2, 4, 6, 8, 10]

💡 Notice: Generator function menggunakan function* dan yield. Setiap kali .next() dipanggil, eksekusi berlanjut sampai yield berikutnya.

Assignment

Buat generator function prima() yang yield bilangan prima tak terbatas. Ambil 10 bilangan prima pertama menggunakan Array.from. Tampilkan hasilnya.

Expected output:

2, 3, 5, 7, 11, 13, 17, 19, 23, 29
JS script.js
Solution
Output