1 declare namespace mem {
2 interface CacheStorage<KeyType extends unknown, ValueType extends unknown> {
3 has(key: KeyType): boolean;
4 get(key: KeyType): ValueType | undefined;
5 set(key: KeyType, value: ValueType): void;
6 delete(key: KeyType): void;
11 ArgumentsType extends unknown[],
12 CacheKeyType extends unknown,
13 ReturnType extends unknown
16 Milliseconds until the cache expires.
20 readonly maxAge?: number;
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.
25 You could for example change it to only cache on the first argument `x => JSON.stringify(x)`.
27 readonly cacheKey?: (...arguments: ArgumentsType) => CacheKeyType;
30 Use a different cache storage. You could for example use a `WeakMap` instead or [`quick-lru`](https://github.com/sindresorhus/quick-lru) for a LRU cache.
34 readonly cache?: CacheStorage<CacheKeyType, {data: ReturnType; maxAge: number}>;
37 Cache rejected promises.
41 readonly cachePromiseRejection?: boolean;
47 [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.
49 @param fn - Function to be memoized.
53 import mem = require('mem');
56 const counter = () => ++i;
57 const memoized = mem(counter);
62 // Cached as it's the same arguments
66 // Not cached anymore as the arguments changed
75 ArgumentsType extends unknown[],
76 ReturnType extends unknown,
77 CacheKeyType extends unknown
79 fn: (...arguments: ArgumentsType) => ReturnType,
80 options?: mem.Options<ArgumentsType, CacheKeyType, ReturnType>
81 ): (...arguments: ArgumentsType) => ReturnType;
84 Clear all cached data of a memoized function.
86 @param fn - Memoized function.
88 clear<ArgumentsType extends unknown[], ReturnType extends unknown>(
89 fn: (...arguments: ArgumentsType) => ReturnType
92 // TODO: Remove this for the next major release