So I am trying to write a general memoizing function in Javascript, using this as my reference material. I've implemented it as instructed:
function memoize(func) {
var memo = {};
var slice = Array.prototype.slice;
return function() {
var args = slice.call(arguments);
if (args in memo)
return memo[args]
else
return (memo[args] = func.apply(this, args));
}
}
function fibonacci(n) {
if (n === 0 || n === 1)
return n;
else
return fibonacci(n - 1) + fibonacci(n - 2);
}
function memoFib = memoize(fibonacci);
console.log("Fibonacci of 6 is " + memoFib(6));
but for the life of me I cannot remember the proper syntax to calling the memoized function. How do I do this? How do I generalize this so that it's the memoized fibonacci function which is always called instead of the original function fibonacci?
You're almost there; you just need to fix your syntax when creating the memoized function. Instead of function memoFib =
, do var memoFib =
(or if ES2015 is an option, const
would be better than var
). And presumably you'll want to have the recursion calling into the memoized version as well, so i updated those as well. In the following code it may look weird that i'm referencing memoFib on a line that comes earlier than the line with var memoFib
but javascript allows that due to hoisting.
function memoize(func) {
var memo = {};
var slice = Array.prototype.slice;
return function() {
var args = slice.call(arguments);
if (args in memo)
return memo[args]
else
return (memo[args] = func.apply(this, args));
}
}
function fibonacci(n) {
if (n === 0 || n === 1)
return n;
else
return memoFib(n - 1) + memoFib(n - 2);
}
var memoFib = memoize(fibonacci);
console.log("Fibonacci of 6 is " + memoFib(6));
And if you want to make absolutely sure no one can ever invoke the nonmemoized version, then you can hide it inside of an IIFE:
const fibonacci = (function () {
function unmemoizedVersion(n) {
if (n === 0 || n === 1)
return n;
else
return fibonacci(n - 1) + fibonacci(n - 2);
}
return memoize(unmemoizedVersion);
})();
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments