Created
February 15, 2010 20:42
-
-
Save wlangstroth/304968 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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