Created
September 6, 2011 15:38
-
-
Save eriwen/1197893 to your computer and use it in GitHub Desktop.
General purpose memoization
This file contains hidden or 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
/** | |
* 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