Last active
June 12, 2022 22:21
-
-
Save 421p/2a32a5aa7cd1ed4bb55413ca34c1b0c3 to your computer and use it in GitHub Desktop.
Lazy / Memoize decorator for TypeScript's getter
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
export function memoize(target: any, prop: string, descriptor: PropertyDescriptor) | |
{ | |
let original = descriptor.get; | |
descriptor.get = function (...args: any[]) | |
{ | |
const privateProp = `__memoized_${prop}`; | |
if (!this.hasOwnProperty(privateProp)) { | |
Object.defineProperty(this, privateProp, { | |
configurable: false, | |
enumerable: false, | |
writable: false, | |
value: original.apply(this, args) | |
}); | |
} | |
return this[privateProp]; | |
}; | |
} |
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
export class Foo{ | |
@memoize get bar() | |
{ | |
return 1 + 1; // will be calculated once and then cached | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Nice, thanks for posting! I also made a decorator to memoize an accessor
get
but I used a closure to store the memoized value: