To memo-ize previous function calls, we can use a nifty memoize
function.
What we're doing in memoize
is utilizing a hash map
(in this case, a plain old JS object) to store previous calculations. The key will be the arguments called-- for example, 5
in fib(5)
, and the value attached will be the result of the callback
. In this example, we utilize the closure pattern so that ...args
are the parameters of the callback function, and not of memoize
.
xxxxxxxxxx
11
const memoize = (callback) => {
let memo = {};
return (args) => {
if (memo[args]) {
return memo[args];
} else {
memo[args] = callback(args);
return memo[args];
}
};
};
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment