๐Ÿ’พ*fibonacci()

generate fibonacci numbers: 1, 1, 2, 3, 5, 8 ...

JSโŸฉ iteration โŸฉ custom generators โŸฉ *fibonacci()

๐Ÿ’พ replit๏ผšfibonacci sequence

๐ŸŒ€ extension๏ผš Iterator - extend built-in iterable iterators.

// โญ๏ธ fibonacci sequence: 1, 1, 2, 3, 5, 8 ... (generator)
// -------------------------------------------------------
function* fibonacci() {

    let [prev, next] = [0, 1];    // โญ๏ธ destructuring assignment

    // โญ๏ธ infinite if `terms` is `undefined`, finite otherwise.
    while (true) {
        yield next;
        [prev, next] = [next, prev + next];
    }

}

// โญ๏ธ nth term of Fibonacci sequence 
// -------------------------------------------------------
function F(n) {
    // return 0 if !(n > 0)
    if (!(n > 0)) return 0;
    // iterate sequence until we get to the nth term
    for (const x of fibonacci()) {
        if (--n <= 0) return x;
    }
}

//  โญ๏ธ export
module.exports = { fibonacci, F }

Last updated