Last active
January 5, 2019 19:54
-
-
Save jeremyben/b4e8592639483d93a3204e579992c4ef 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
/** | |
* Defines a getter on a specified object that will be created upon first use. | |
* | |
* https://developer.mozilla.org/en-US/docs/Mozilla/JavaScript_code_modules/XPCOMUtils.jsm#defineLazyGetter() | |
* https://dxr.mozilla.org/mozilla-central/source/js/xpconnect/loader/XPCOMUtils.jsm#120 | |
*/ | |
function defineMemoizedGetter(object: any, prop: string, fn: Function) { | |
let redefining = false | |
Object.defineProperty(object, prop, { | |
get: function() { | |
if (!redefining) { | |
// Make sure we don't get into an infinite recursion loop | |
redefining = true | |
const value = fn.apply(object) | |
Object.defineProperty(object, prop, { | |
configurable: true, | |
enumerable: true, | |
value, | |
writable: true | |
}) | |
return value | |
} | |
}, | |
configurable: true, | |
enumerable: true | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment