Skip to content

Instantly share code, notes, and snippets.

@vectart
Created November 15, 2011 11:38
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save vectart/1366863 to your computer and use it in GitHub Desktop.
memoize = function(func, context, single) {
function memoizeArg (argPos, depth) {
var cache = {};
return function () {
if (argPos == 0 && depth == 0) {
argPos = arguments.length;
}
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)) {
if (single) {
cache = {};
}
cache[arguments[argPos]] = memoizeArg(argPos - 1, depth + 1);
}
return cache[arguments[argPos]].apply(this, arguments);
}
}
}
return memoizeArg(func.length - 1, 0);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment