Created
May 25, 2010 20:04
-
-
Save tiegz/413610 to your computer and use it in GitHub Desktop.
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
/* 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