Skip to content

Instantly share code, notes, and snippets.

@tiegz
Created May 25, 2010 20:04
Show Gist options
  • Save tiegz/413610 to your computer and use it in GitHub Desktop.
Save tiegz/413610 to your computer and use it in GitHub Desktop.
/* Generates a memoizable getter. */
Object.prototype.memoize = function(key, func) {
var __key__ = "__" + key + "__";
this.__defineGetter__(key, function() {
if (this[__key__]) return this[__key__];
this[__key__] = func();
return this[__key__];
});
};
/***********/
/* Example */
/***********/
var n = {};
n.memoize('ichi', function() {
console.log("Setting to 1");
return 1;
});
console.log(n.ichi);
> Setting to 1
> 1
console.log(n.ichi);
> 1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment