Skip to content

Instantly share code, notes, and snippets.

@eriwen
Created September 6, 2011 15:38
Show Gist options
  • Save eriwen/1197893 to your computer and use it in GitHub Desktop.
Save eriwen/1197893 to your computer and use it in GitHub Desktop.
General purpose memoization
/**
* A general-purpose function to enable a function to use memoization. The function must use explicit, string-serializable parameters
* @param func {Function} to be memoized
* @parma context {Object} the context for the memoized function to execute within
*/
function memoize(func, context) {
function memoizeArg (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);
}
}
}
// JScript doesn't grok the arity property, but uses length instead
var arity = func.arity || func.length;
return memoizeArg(arity - 1);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment