Skip to content

Instantly share code, notes, and snippets.

@alexsanqp
Created April 17, 2020 00:10
Show Gist options
  • Save alexsanqp/b12e92fdd4d257ea394688a1eb456a9d to your computer and use it in GitHub Desktop.
Save alexsanqp/b12e92fdd4d257ea394688a1eb456a9d to your computer and use it in GitHub Desktop.
export const memorizeFn = <T extends () => void>(fn: T, size = 5, duration = 0): any => {
const cache: Map<string, any> = new Map<string, any>();
if (duration) {
setInterval(() => cache.clear(), duration);
}
return (...args: any[]): any => {
const key: string = JSON.stringify(args);
if (!cache.has(key)) {
cache.set(key, (fn as any)(...args));
}
try {
return cache.get(key);
} finally {
if (cache.size > size) {
cache.delete(cache.keys().next().value);
}
}
};
};
export function Memorize(opts: { size?: number; duration?: number } = {}): any {
return (target: object, name: string, descriptor: PropertyDescriptor): PropertyDescriptor => {
descriptor.value = memorizeFn(target[name], opts.size, opts.duration);
return descriptor;
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment