-
Notifications
You must be signed in to change notification settings - Fork 118
/
memoize.js
39 lines (37 loc) · 1.2 KB
/
memoize.js
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
// Given a function fn, return a memoized version of that function.
// A memoized function is a function that will never be called twice with the same inputs.
// Instead, it will return a cached value.
// fn can be any function and there are no constraints on what type of values it accepts.
// Inputs are considered identical if they are === to each other.
/**
* @param {Function} fn
* @return {Function}
*/
function memoize(fn) {
const cache = new Map();
const result = Symbol('result');
return function (...args) {
let currentCacheLevel = cache;
args.forEach(arg => {
if (!currentCacheLevel.has(arg)) {
currentCacheLevel.set(arg, new Map());
}
currentCacheLevel = currentCacheLevel.get(arg);
});
if (!currentCacheLevel.has(result)) {
currentCacheLevel.set(result, fn(...args));
}
return currentCacheLevel.get(result);
};
}
let callCount = 0;
const memoizedFn = memoize(function (...arr) {
++callCount;
return arr.reduce((a, b) => a + b, 0);
});
console.log(memoizedFn(1, 1, 1)); // 3
console.log(memoizedFn(1, 1)); // 2
console.log(memoizedFn(1)); // 1
console.log(memoizedFn(1, 1)); // 2
console.log(memoizedFn(1, 1, 1)); // 3
console.log(callCount); // 3