Skip to content

Instantly share code, notes, and snippets.

@tgriesser
Created December 6, 2019 19:34
Show Gist options
  • Save tgriesser/dd81e1cc44acfb4c690ff598e5c54afc to your computer and use it in GitHub Desktop.
Save tgriesser/dd81e1cc44acfb4c690ff598e5c54afc to your computer and use it in GitHub Desktop.
cache result getter
/**
* A cache result decorator means the value is lazily evaluated once and
* the result is cached on the class instance.
*/
export const cacheResult = <T>(
target: T,
key: PropertyKey,
descriptor: PropertyDescriptor
): void => {
if (!descriptor) {
descriptor = Object.getOwnPropertyDescriptor(
target,
key
) as PropertyDescriptor
}
const originalMethod = descriptor.get
const isStatic = Object.getPrototypeOf(target) === Function.prototype
if (isStatic) {
throw new Error(`Don't use @cacheResult decorator on static properties`)
}
if (!originalMethod) {
throw new Error('@cacheResult can only decorate getters!')
} else if (!descriptor.configurable) {
throw new Error('@cacheResult target must be configurable')
} else {
descriptor.get = function() {
// eslint-disable-next-line
const value = originalMethod.apply(this, arguments as any)
const newDescriptor: PropertyDescriptor = {
configurable: false,
enumerable: false,
value,
}
Object.defineProperty(this, key, newDescriptor)
return value
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment