Skip to content

Instantly share code, notes, and snippets.

@jackysee
Created January 8, 2010 02:14
Show Gist options
  • Save jackysee/271799 to your computer and use it in GitHub Desktop.
Save jackysee/271799 to your computer and use it in GitHub Desktop.
/*
Simple memoize function for function caching
- use args array as cache key
- Usage:
function fib(n){
return n < 2? n: fib(n-2) + fib(n-1);
}
fib = namespace.memoize(fib);
*/
var namespace = {};
namespace.memoize = function(f){
return function(){
var args = Array.prototype.slice.call(arguments),
cache = this.memoizeCache;
if(!cache) cache = this.memoizeCache = {};
if(!cache[args]) cache[args] = f.apply(this, arguments);
return cache[args];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment