Skip to content

Instantly share code, notes, and snippets.

@Sangrene
Created June 23, 2020 13:41
Show Gist options
  • Save Sangrene/54a8eaed5ea0b0f39c20678435ecb243 to your computer and use it in GitHub Desktop.
Save Sangrene/54a8eaed5ea0b0f39c20678435ecb243 to your computer and use it in GitHub Desktop.
To cache a function result based on time and arguments
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