1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
|
...
const cacheStore = new WeakMap<AnyFunction, CacheStorage<any, any>>();
export default function mem<
FunctionToMemoize extends AnyFunction,
CacheKeyType,
>(
fn: FunctionToMemoize,
{
cacheKey,
cache = new Map(),
maxAge,
}: Options<FunctionToMemoize, CacheKeyType> = {},
): FunctionToMemoize {
if (typeof maxAge === 'number') {
mapAgeCleaner(cache as unknown as Map<CacheKeyType, ReturnType<FunctionToMemoize>>);
}
const memoized = function (this: any, ...arguments_: Parameters<FunctionToMemoize>): ReturnType<FunctionToMemoize> {
const key = cacheKey ? cacheKey(arguments_) : arguments_[0] as CacheKeyType;
const cacheItem = cache.get(key);
if (cacheItem) {
return cacheItem.data; // eslint-disable-line @typescript-eslint/no-unsafe-return
}
const result = fn.apply(this, arguments_) as ReturnType<FunctionToMemoize>;
cache.set(key, {
data: result,
maxAge: maxAge ? Date.now() + maxAge : Number.POSITIVE_INFINITY,
});
return result; // eslint-disable-line @typescript-eslint/no-unsafe-return
} as FunctionToMemoize;
mimicFn(memoized, fn, {
ignoreNonConfigurable: true,
});
cacheStore.set(memoized, cache);
return memoized;
}
|