Skip to content

Instantly share code, notes, and snippets.

@wlangstroth
Created February 15, 2010 20:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wlangstroth/304968 to your computer and use it in GitHub Desktop.
Save wlangstroth/304968 to your computer and use it in GitHub Desktop.
// Crockford's
function memoizer(memo, fundamental) {
var shell = function (n) {
var result = memo[n];
if (typeof result !== 'number') {
result = fundamental(shell, n);
memo[n] = result;
}
return result;
};
return shell;
}
// John Hann's
// memoize: a general-purpose function to enable a function to use memoization
// func: the function to be memoized
// context: the context for the memoized function to execute within
// Note: the function must use explicit, primitive parameters (or objects
// that generate unique strings in a toString() method)
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