X-Git-Url: https://git.piment-noir.org/?a=blobdiff_plain;f=src%2Futils.ts;h=a0a9e530131cbe78df7401dff80452eef16e8634;hb=d91689fda0fa7a85014ac25276cf2cf0a9d81ce2;hp=d7ce5a210f2dea09290fd90a5f4eb64fcb2162d5;hpb=bfc75ccaf49d915d2b7e73c92360787b3245321a;p=poolifier.git diff --git a/src/utils.ts b/src/utils.ts index d7ce5a21..a0a9e530 100644 --- a/src/utils.ts +++ b/src/utils.ts @@ -250,3 +250,27 @@ export const min = (...args: number[]): number => */ export const max = (...args: number[]): number => args.reduce((maximum, num) => (maximum > num ? maximum : num), -Infinity) + +/** + * Wraps a function so that it can only be called once. + * + * @param fn - The function to wrap. + * @param context - The context to bind the function to. + * @returns The wrapped function. + * @internal + */ +// eslint-disable-next-line @typescript-eslint/no-explicit-any +export const once = ( + fn: (...args: A) => R, + context: T +): ((...args: A) => R) => { + let result: R + return (...args: A) => { + if (fn != null) { + result = fn.apply(context, args) + ;(fn as unknown as undefined) = (context as unknown as undefined) = + undefined + } + return result + } +}