Skip to content

Instantly share code, notes, and snippets.

@AdamMadrzejewski
Created September 5, 2014 18:36
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 AdamMadrzejewski/510798d24c1eba1eabc5 to your computer and use it in GitHub Desktop.
Save AdamMadrzejewski/510798d24c1eba1eabc5 to your computer and use it in GitHub Desktop.
cached prototype using clousure
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