Created
June 23, 2020 13:41
-
-
Save Sangrene/54a8eaed5ea0b0f39c20678435ecb243 to your computer and use it in GitHub Desktop.
To cache a function result based on time and arguments
This file contains 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
type AnyFunction = (...args: any[]) => any; | |
type GetReturnType<T extends AnyFunction> = T extends (...args: any[]) => infer R ? R : any; | |
export const timeCacheResult = <T extends AnyFunction>( | |
cache: Map<any, { until: number; value: any }>, | |
cacheTime: number, | |
func: T, | |
): T => { | |
return function(...args: any[]) { | |
const curTime = new Date().getTime(); | |
const hash = func.name + [].join.call(args); | |
const cacheEntry = cache.get(hash); | |
if (cacheEntry !== undefined && cacheEntry.until > curTime) { | |
return cacheEntry.value as GetReturnType<T>; | |
} | |
const result = func.apply(this, args); | |
cache.set(hash, { until: curTime + cacheTime, value: result }); | |
return result as GetReturnType<T>; | |
} as T; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment