Created
September 9, 2011 15:53
-
-
Save meagar/1206576 to your computer and use it in GitHub Desktop.
Caching wrapper redux
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
Function.prototype.cachify = function () { | |
var cache = {}, self = this; | |
return function (arg) { | |
if (arg in cache) { | |
console.info('cache hit'); | |
return cache[arg]; | |
} | |
return cache[arg] = self.call(self, arg); | |
}; | |
}; | |
isPrime = isPrime.cachify(); | |
sin = Math.sin.cachify(); | |
console.info(isPrime(3)); | |
console.info(isPrime(3)); // cache hit | |
console.info(sin(60)); | |
console.info(sin(60)); // cache hit |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment