Write the answers down
You are working out the tenth Fibonacci number the way you learned it: the tenth
needs the ninth and the eighth, the ninth needs the eighth again, and the eighth
keeps showing up. You are doing the same small sums an enormous number of times,
and the work explodes as n grows.
Keep a cheat sheet. The first time you work out a number, write the answer down. The next time you are asked for it, read it back instead of working it out again. Nothing is recomputed, so the runaway work collapses to a single pass.
The self-similar step is the definition itself: fib(n) is fib(n - 1) plus
fib(n - 2). The base case needs no sheet — fib(0) is 0 and fib(1) is 1,
answered directly.
Shrink the input to n - 1 and n - 2, and trust those calls to return the
right values. The only difference from plain recursion is where the answer goes:
look on the sheet before you recurse, and store the result after you compute it.
const cache = {};
function fib(n) {
if (n <= 1) {
return n;
}
if (cache[n] === undefined) {
cache[n] = fib(n - 1) + fib(n - 2);
}
return cache[n];
}
Each value is computed once and read back every other time, so a function that took exponential steps now takes linear ones.
Export fib from index.js. It returns the nth Fibonacci number, counting
fib(0) as 0 and fib(1) as 1.
Challenge
The Fibonacci sequence is defined by itself: each number is the two before it
added together, so a plain recursion computes the same values over and over.
Export a fib function from index.js that writes each answer down and reads
it back instead of recomputing.
fib takes a non-negative whole number n and returns the nth Fibonacci
number, with fib(0) as 0 and fib(1) as 1. Cache every result the first
time you compute it, and check the cache before recursing.