-
-
Notifications
You must be signed in to change notification settings - Fork 381
Expand file tree
/
Copy pathmemorize.js
More file actions
49 lines (38 loc) · 1.03 KB
/
memorize.js
File metadata and controls
49 lines (38 loc) · 1.03 KB
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
47
48
49
/** @typedef {import("../index").EXPECTED_ANY} EXPECTED_ANY */
const cacheStore = new WeakMap();
/**
* @template T
* @typedef {(...args: EXPECTED_ANY) => T} FunctionReturning
*/
/**
* @template T
* @param {FunctionReturning<T>} fn memorized function
* @param {({ cache?: Map<string, { data: T }> } | undefined)=} cache cache
* @param {((value: T) => T)=} callback callback
* @returns {FunctionReturning<T>} new function
*/
function memorize(fn, { cache = new Map() } = {}, callback = undefined) {
/**
* @param {EXPECTED_ANY[]} arguments_ args
* @returns {EXPECTED_ANY} result
*/
const memoized = (...arguments_) => {
const [key] = arguments_;
const cacheItem = cache.get(key);
if (cacheItem) {
return cacheItem.data;
}
// @ts-expect-error
let result = fn.apply(this, arguments_);
if (callback) {
result = callback(result);
}
cache.set(key, {
data: result,
});
return result;
};
cacheStore.set(memoized, cache);
return memoized;
}
module.exports = memorize;