UNPKG

typedash

Version:

modern, type-safe collection of utility functions

1 lines 1.57 kB
{"version":3,"sources":["../../src/functions/memoize/memoize.ts"],"names":[],"mappings":";AAQO,SAAS,QAEd,IACA,kBACW;AACX,QAAM,QAAQ,oBAAI,IAAoC;AAEtD,SAAO,SAAS,oBACX,MACoB;AACvB,UAAM,WAAoB,mBACtB,iBAAiB,GAAG,IAAI,IACxB,KAAK,CAAC;AAEV,QAAI,MAAM,IAAI,QAAQ,GAAG;AAEvB,aAAO,MAAM,IAAI,QAAQ;AAAA,IAC3B;AAEA,UAAM,SAAS,GAAG,GAAG,IAAI;AACzB,UAAM,IAAI,UAAU,MAAM;AAG1B,WAAO;AAAA,EACT;AACF","sourcesContent":["import { AnyFunction } from '../../types/_internal';\n\n/**\n * Memoizes a function.\n * @param fn The function to memoize.\n * @param cacheKeyResolver An optional function used to resolve the cache key. Defaults to the first argument in the function call.\n * @returns The memoized function.\n */\nexport function memoize<TFunction extends AnyFunction>(\n // eslint-disable-next-line unicorn/prevent-abbreviations -- `function` is a reserved word\n fn: TFunction,\n cacheKeyResolver?: (...args: Parameters<TFunction>) => string\n): TFunction {\n const cache = new Map<unknown, ReturnType<TFunction>>();\n\n return function memoizedFunction(\n ...args: Parameters<TFunction>\n ): ReturnType<TFunction> {\n const cacheKey: unknown = cacheKeyResolver\n ? cacheKeyResolver(...args)\n : args[0];\n\n if (cache.has(cacheKey)) {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-return\n return cache.get(cacheKey)!;\n }\n\n const result = fn(...args) as ReturnType<TFunction>;\n cache.set(cacheKey, result);\n\n // eslint-disable-next-line @typescript-eslint/no-unsafe-return\n return result;\n } as TFunction;\n}\n"]}