Simple memoization

We will work with the Fibonacci function we mentioned previously, which is a simple case: it receives a single numeric parameter. This function is as follows:

function fib(n) {  if (n == 0) {    return 0;  } else if (n == 1) {    return 1;  } else {    return fib(n - 2) + fib(n - 1);  }}

The solution we created previously was general in concept, but particularly in its implementation: we had to directly modify the code of the function in order to take advantage of said memoization. Now, we should look into a way of doing this automatically, in the same fashion as we do it with other wrapped functions. The solution would be a memoize() function that wraps any other function in order to apply memoization:

const memoize = fn => { let cache ...

Get Mastering JavaScript Functional Programming - Second Edition now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.