Created
September 5, 2014 18:36
-
-
Save AdamMadrzejewski/510798d24c1eba1eabc5 to your computer and use it in GitHub Desktop.
cached prototype using clousure
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
Function.prototype.cached = function() { | |
var self = this, //"this" refers to the original function | |
cache = {}; //our local, lexically scoped cache storage | |
return function(args) { | |
if(args in cache) return cache[args]; | |
return cache[args] = self(args); | |
}; | |
}; | |
Math.sin = Math.sin.cached(); | |
Math.sin(1) // => 0.8414709848078965 | |
Math.sin(1) // => 0.8414709848078965 this time pulled from cache |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment