Now we can wrap our fibonacci
function with the memoize
function for a more efficient solution. During an interview, it's best to bring up the use of this pattern whenever there's several repeating subproblems.
xxxxxxxxxx
23
const memoize = (callback) => {
let memo = {};
return (args) => {
if (memo[args]) {
return memo[args];
} else {
memo[args] = callback(args);
return memo[args];
}
};
};
​
function fibonacci(num) {
if (num < 0) throw "num must be >= 0";
if (num === 0) return 0;
if (num === 1) return 1;
​
return fibonacci(num - 1) + fibonacci(num - 2);
}
​
const memoizedFib = memoize(fibonacci);
const result = memoizedFib(30);
console.log(result);
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment