Created
September 4, 2020 17:50
-
-
Save m3g4p0p/f3cad151498352c219768e22f6a65bee to your computer and use it in GitHub Desktop.
lazily get object properties
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
const lazyGetter = (getters) => Object.create(null, Object | |
.keys(getters) | |
.reduce((result, key) => Object.assign(result, { | |
[key]: { | |
get () { | |
const value = getters[key].call(this) | |
Object.defineProperty(this, key, { value }) | |
return value | |
}, | |
configurable: true | |
} | |
}), {})) | |
const foo = lazyGetter({ | |
spam: () => console.log('spam') || 42, | |
eggs: () => console.log('eggs') || 'baz', | |
}) | |
console.log(foo.spam, foo.spam, foo.eggs, foo.eggs, foo.spam) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment