UNPKG

typedash

Version:

modern, type-safe collection of utility functions

1 lines 1.27 kB
{"version":3,"sources":["../../src/functions/once/once.ts"],"names":[],"mappings":";AASO,SAAS,KAEd,IACW;AACX,MAAI;AACJ,MAAI,gBAAgB;AAEpB,SAAQ,IAAI,SAAgC;AAC1C,QAAI,CAAC,eAAe;AAElB,eAAS,GAAG,GAAG,IAAI;AACnB,sBAAgB;AAAA,IAClB;AAGA,WAAO;AAAA,EACT;AACF","sourcesContent":["import { AnyFunction } from '../../types/_internal';\n\n/**\n * Invokes the given function only once, no matter how many times it's called.\n * If it was already invoked before, returns the result from the first invocation.\n * @template TFunction The type of the function to be invoked.\n * @param fn The function to be invoked.\n * @returns The result of the first invocation of the function.\n */\nexport function once<TFunction extends AnyFunction>(\n // eslint-disable-next-line unicorn/prevent-abbreviations -- `function` is a reserved word\n fn: TFunction\n): TFunction {\n let result: ReturnType<TFunction> | undefined;\n let hasBeenCalled = false;\n\n return ((...args: Parameters<TFunction>) => {\n if (!hasBeenCalled) {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment\n result = fn(...args);\n hasBeenCalled = true;\n }\n\n // eslint-disable-next-line @typescript-eslint/no-unsafe-return\n return result;\n }) as TFunction;\n}\n"]}