Skip to content

Instantly share code, notes, and snippets.

@furf
Created May 7, 2009 14:16
Show Gist options
  • Save furf/108105 to your computer and use it in GitHub Desktop.
Save furf/108105 to your computer and use it in GitHub Desktop.
/**
* memoize
* http://unscriptable.com/index.php/2009/05/01/a-better-javascript-memoizer/
*/
var memoize = function (func, context) {
var memoizeArg = function (argPos) {
var cache = {};
return function () {
if (argPos === 0) {
if (!(arguments[argPos] in cache)) {
cache[arguments[argPos]] = func.apply(context, arguments);
}
return cache[arguments[argPos]];
}
else {
if (!(arguments[argPos] in cache)) {
cache[arguments[argPos]] = memoizeArg(argPos - 1);
}
return cache[arguments[argPos]].apply(this, arguments);
}
};
};
var arity = func.arity || func.length;
return memoizeArg(arity - 1);
};
/**
* Example
*/
var fibonacci = memoize(function(n) {
return n < 2 ? n : fibonacci(n - 1) + fibonacci(n - 2);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment