Created
January 8, 2010 02:14
-
-
Save jackysee/271799 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
/* | |
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