Skip to content

Commit 0ab6601

Browse files
Update MemoizeII.js
1 parent 5604e6b commit 0ab6601

File tree

1 file changed

+25
-0
lines changed

1 file changed

+25
-0
lines changed

L-A/0014 Memoize II/MemoizeII.js

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1 +1,26 @@
11

2+
const RES = Symbol("result");
3+
4+
/**
5+
* @param {Function} fn
6+
*/
7+
function memoize(fn) {
8+
const globalCache = new Map();
9+
10+
return (...params) => {
11+
let currentCache = globalCache;
12+
for(const param of params) {
13+
if (!currentCache.has(param)) {
14+
currentCache.set(param, new Map());
15+
}
16+
currentCache = currentCache.get(param);
17+
}
18+
19+
if (currentCache.has(RES)) return currentCache.get(RES);
20+
21+
const result = fn(...params);
22+
23+
currentCache.set(RES, result);
24+
return result;
25+
}
26+
}

0 commit comments

Comments
 (0)