Created
July 4, 2018 07:04
-
-
Save vlio20/33f8723a1c56368e4dd65f6866f2da83 to your computer and use it in GitHub Desktop.
Typescript memoize decorator
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 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