( fn: (...args: Args) => Promise<R>, keyFn: (...args: Args) => string = (...args) => JSON.stringify(args) )
| 11 | * rejection is evicted so failures are not memoized. |
| 12 | */ |
| 13 | export function memoizeAsync<Args extends any[], R>( |
| 14 | fn: (...args: Args) => Promise<R>, |
| 15 | keyFn: (...args: Args) => string = (...args) => JSON.stringify(args) |
| 16 | ): (...args: Args) => Promise<R> { |
| 17 | const store = new Map<string, Promise<R>>(); |
| 18 | |
| 19 | return (...args: Args): Promise<R> => { |
| 20 | const key = keyFn(...args); |
| 21 | const existing = store.get(key); |
| 22 | if (existing) return existing; |
| 23 | |
| 24 | const promise = fn(...args).catch((error) => { |
| 25 | store.delete(key); |
| 26 | throw error; |
| 27 | }); |
| 28 | store.set(key, promise); |
| 29 | return promise; |
| 30 | }; |
| 31 | } |
no outgoing calls
no test coverage detected