Skip to content

Instantly share code, notes, and snippets.

@fauxparse
Created August 9, 2011 16:23
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 fauxparse/1134489 to your computer and use it in GitHub Desktop.
Save fauxparse/1134489 to your computer and use it in GitHub Desktop.
Multi-param memoization
Function.prototype.cached = function() {
var f = this,
cache = {};
function get(c, a, i) {
var l = a.length, k = a[i];
if (l == 0) {
return f();
} else if (i==l) {
return (k in c) ? c[k] : (c[k] = f.apply(this, a));
} else {
if (!(k in c)) c[k] = {};
return get(c[k], a, i+1);
}
}
return function() {
return get(cache, [].slice.call(arguments), 0);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment