Wednesday, July 22, 2020

Lazy-evaluating iterators with Array.from

function* fibGenerator(qualifierFunc) {
    let a = 0;
    let b = 1;

    for (;;) {
        if (qualifierFunc && !qualifierFunc(a)) {
            return;
        }
        console.log('gen fib', a);

        yield a;
        const n = a;
        a += b;
        b = n;
    }
}

Array.from(fibGenerator(n => n <= 13), v => console.log('hey', v));

console.log('----');

Array.from(fibGenerator(n => n <= 13)).map(v => console.log('hey', v));


gen fib 0
hey 0
gen fib 1
hey 1
gen fib 1
hey 1
gen fib 2
hey 2
gen fib 3
hey 3
gen fib 5
hey 5
gen fib 8
hey 8
gen fib 13
hey 13
----
gen fib 0
gen fib 1
gen fib 1
gen fib 2
gen fib 3
gen fib 5
gen fib 8
gen fib 13
hey 0
hey 1
hey 1
hey 2
hey 3
hey 5
hey 8
hey 13

The first Array.from is better as it does not allocate memory. Don't defeat the purpose of iterator's lazy-evaluating capability.

No comments:

Post a Comment