Last active
September 30, 2021 22:13
-
-
Save dscheerens/8791470290d2a051934fb45890b23601 to your computer and use it in GitHub Desktop.
TypeScript memoize decorator for get accessor functions
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
const GLOBAL_MEMOIZATION_MAP = new WeakMap<object, Map<string, unknown>>(); | |
// tslint:disable-next-line:ban-types | |
export function Memoize<T extends { constructor: Function }>( | |
target: T, | |
propertyKey: string, | |
descriptor: PropertyDescriptor, | |
): PropertyDescriptor { | |
const originalGet = descriptor.get; // tslint:disable-line: no-unbound-method | |
if (!originalGet) { | |
throw new Error(`Cannot apply @Memoize decorator to '${target.constructor.name}.${propertyKey}' since it has no get accessor`); | |
} | |
return { | |
...descriptor, | |
get(this: object): unknown { | |
let localMemoizationMap = GLOBAL_MEMOIZATION_MAP.get(this); | |
if (!localMemoizationMap) { | |
localMemoizationMap = new Map<string, unknown>(); | |
GLOBAL_MEMOIZATION_MAP.set(this, localMemoizationMap); | |
} | |
if (localMemoizationMap.has(propertyKey)) { | |
return localMemoizationMap.get(propertyKey); | |
} | |
const value = originalGet.call(this); | |
localMemoizationMap.set(propertyKey, value); | |
return value; | |
}, | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment