Skip to content

Instantly share code, notes, and snippets.

@dscheerens
Last active September 30, 2021 22:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dscheerens/8791470290d2a051934fb45890b23601 to your computer and use it in GitHub Desktop.
Save dscheerens/8791470290d2a051934fb45890b23601 to your computer and use it in GitHub Desktop.
TypeScript memoize decorator for get accessor functions
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