import { stringify } from 'extra-json-stable-stringify' import { HashMap } from '@blackglory/structures' type VerboseResult = [value: T, isReuse: boolean] interface IReusePendingPromisesOptions { createKey?: (args: Args) => unknown verbose?: true } export function reusePendingPromises( fn: (...args: Args) => PromiseLike , options: IReusePendingPromisesOptions & { verbose: true } ): (...args: Args) => Promise> export function reusePendingPromises( fn: (...args: Args) => PromiseLike , options: IReusePendingPromisesOptions & { verbose: false } ): (...args: Args) => Promise export function reusePendingPromises( fn: (...args: Args) => PromiseLike , options: Omit, 'verbose'> ): (...args: Args) => Promise export function reusePendingPromises( fn: (...args: Args) => PromiseLike ): (...args: Args) => Promise export function reusePendingPromises( fn: (...args: Args) => PromiseLike , options?: IReusePendingPromisesOptions ): (...args: Args) => Promise> { const pendings = new HashMap>(options?.createKey ?? stringify) return async function ( this: unknown , ...args: Args ): Promise> { const [value, isReuse] = await reusableFunction.apply(this, args) return options?.verbose ? [value, isReuse] : value } async function reusableFunction( this: unknown , ...args: Args ): Promise<[value: T, reuse: boolean]> { const result = pendings.get(args) if (result) { return [await result, true] } else { const promise = Promise.resolve(fn.apply(this, args)) .finally(() => pendings.delete(args)) pendings.set(args, promise) return [await promise, false] } } }