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 the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.