Skip to content

Instantly share code, notes, and snippets.

@vlio20
Created July 4, 2018 07:04
Show Gist options
  • Save vlio20/33f8723a1c56368e4dd65f6866f2da83 to your computer and use it in GitHub Desktop.
Save vlio20/33f8723a1c56368e4dd65f6866f2da83 to your computer and use it in GitHub Desktop.
Typescript memoize decorator
const MEMOIZED_VALUE_KEY = '_memoizedValue';
export function memoize(expirationTimeMs: number = 60000) {
return (target: any, propertyName: string, descriptor: TypedPropertyDescriptor<any>) => {
if (descriptor.value != null) {
const originalMethod = descriptor.value;
const fn: any = function (...args: any[]) {
const key = MEMOIZED_VALUE_KEY + '_' + JSON.stringify(args);
if (!fn[key]) {
fn[key] = originalMethod.apply(this, args);
setTimeout(() => clearMemoizedValue(fn, key), expirationTimeMs);
}
return fn[key];
};
descriptor.value = fn;
return descriptor;
} else {
throw Error('Only put the @memoize decorator on a method.');
}
};
}
export function clearMemoizedValue(method: any, key: string) {
delete method[key];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment