Created
April 17, 2020 00:10
-
-
Save alexsanqp/b12e92fdd4d257ea394688a1eb456a9d to your computer and use it in GitHub Desktop.
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
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