Skip to content

Instantly share code, notes, and snippets.

@m3g4p0p
Created September 4, 2020 17:50
Show Gist options
  • Save m3g4p0p/f3cad151498352c219768e22f6a65bee to your computer and use it in GitHub Desktop.
Save m3g4p0p/f3cad151498352c219768e22f6a65bee to your computer and use it in GitHub Desktop.
lazily get object properties
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