It was a piece of code to read :)
You probably know that memoization stores the result of the function, so the next time the function is called, it does not need to calculate the answer, it can just view it.
So, we need to store the answers for the fibonacci function, which takes an int and returns an int.
var fibonacci = memoizer([0, 1], function (test, n) { return test(n - 1) + test(n - 2); });
Calls memoizer with the original memo array, mapping fib (0) โ 0 and fib (1) โ 1.
The rest defines an unnamed function that takes a function and a number. "test" is a bad name, it should be "recursive_fibonacci_helper" :)
This unnamed function becomes the "main" parameter. The memoizer function returns a function (shell) that takes an int argument. This eventually becomes a fibonacci function.
So, when someone says "fibonacci (5)". They are really called a "shell (5)." An important part of closures is that the โfundamentalโ and โmemorabiliaโ are already connected.
So what does a shell do?
He searches the notes table to see if he has already calculated the answer for this input. If he sees the answer (== 'number'), he returns it. Otherwise, it calculates it and saves it in the notes table. memo[n] = result actually stores the calculated result in the memoization table.
source share