index.d.ts 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. export interface CacheStorage<
  2. KeyType extends unknown,
  3. ValueType extends unknown
  4. > {
  5. has(key: KeyType): boolean;
  6. get(key: KeyType): ValueType | undefined;
  7. set(key: KeyType, value: ValueType): void;
  8. delete(key: KeyType): void;
  9. clear?: () => void;
  10. }
  11. export interface Options<
  12. ArgumentsType extends unknown[],
  13. CacheKeyType extends unknown,
  14. ReturnType extends unknown
  15. > {
  16. /**
  17. * Milliseconds until the cache expires.
  18. *
  19. * @default Infinity
  20. */
  21. readonly maxAge?: number;
  22. /**
  23. * Determines the cache key for storing the result based on the function arguments. By default, if there's only one argument and it's a [primitive](https://developer.mozilla.org/en-US/docs/Glossary/Primitive), it's used directly as a key, otherwise it's all the function arguments JSON stringified as an array.
  24. *
  25. * You could for example change it to only cache on the first argument `x => JSON.stringify(x)`.
  26. */
  27. readonly cacheKey?: (...arguments: ArgumentsType) => CacheKeyType;
  28. /**
  29. * Use a different cache storage. Must implement the following methods: `.has(key)`, `.get(key)`, `.set(key, value)`, `.delete(key)`, and optionally `.clear()`. You could for example use a `WeakMap` instead or [`quick-lru`](https://github.com/sindresorhus/quick-lru) for a LRU cache.
  30. *
  31. * @default new Map()
  32. */
  33. readonly cache?: CacheStorage<CacheKeyType, ReturnType>;
  34. /**
  35. * Cache rejected promises.
  36. *
  37. * @default false
  38. */
  39. readonly cachePromiseRejection?: boolean;
  40. }
  41. /**
  42. * [Memoize](https://en.wikipedia.org/wiki/Memoization) functions - An optimization used to speed up consecutive function calls by caching the result of calls with identical input.
  43. *
  44. * @param fn - Function to be memoized.
  45. */
  46. declare const mem: {
  47. <
  48. ArgumentsType extends unknown[],
  49. ReturnType extends unknown,
  50. CacheKeyType extends unknown
  51. >(
  52. fn: (...arguments: ArgumentsType) => ReturnType,
  53. options?: Options<ArgumentsType, CacheKeyType, ReturnType>
  54. ): (...arguments: ArgumentsType) => ReturnType;
  55. /**
  56. * Clear all cached data of a memoized function.
  57. *
  58. * @param fn - Memoized function.
  59. */
  60. clear<ArgumentsType extends unknown[], ReturnType extends unknown>(
  61. fn: (...arguments: ArgumentsType) => ReturnType
  62. ): void;
  63. };
  64. export default mem;