| 17 | // reuse previous promise when a request call |
| 18 | // and previous request not completed |
| 19 | export const reuseable = <F extends (...args: any[]) => Promise<any>>( |
| 20 | func: F, |
| 21 | computeCacheKey: (...args: Parameters<F>) => string = defaultComputeCacheKey |
| 22 | ) => { |
| 23 | const cache = new Map<string, ReturnType<F>>(); |
| 24 | |
| 25 | return function f(this: unknown, ...args: Parameters<F>): ReturnType<F> { |
| 26 | const key = computeCacheKey(...args); |
| 27 | if (cache.has(key)) { |
| 28 | return cache.get(key)!; |
| 29 | } |
| 30 | |
| 31 | const promise = func.call(this, ...args) as ReturnType<F>; |
| 32 | cache.set(key, promise); |
| 33 | |
| 34 | if (promise instanceof Promise) { |
| 35 | return promise.finally(() => cache.delete(key)) as ReturnType<F>; |
| 36 | } else { |
| 37 | cache.delete(key); |
| 38 | return promise; |
| 39 | } |
| 40 | }; |
| 41 | }; |
| 42 | |
| 43 | export const throttle = <T extends (...args: any[]) => any>( |
| 44 | func: T, |