DEV Community

Discussion on: What’s your alternative solution? Challenge #16

Collapse
 
pbouillon profile image
Pierre Bouillon

May I suggest a recursive version with a cache ? I don't know if this is a huge improvement in this case but 🤷

function fibonacci (index) {

    cache = [0, 1]

    function eval_fib_rank (rank) {
        return rank in cache
            ? cache[rank]
            : cache[rank] = eval_fib_rank(rank - 1) + eval_fib_rank(rank - 2)
    }

    eval_fib_rank(index);

    return cache;
}

console.log(fibonacci (9))