forked from HowProgrammingWorks/Memoization
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path9-countMemoize.js
More file actions
49 lines (46 loc) · 1.05 KB
/
9-countMemoize.js
File metadata and controls
49 lines (46 loc) · 1.05 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
'use strict';
const argKey = x => (x.toString() + ':' + typeof(x));
const generateKey = arg => arg.map(argKey).join('|');
const countMemoize = (fn, max) => {
const cache = new Map();
return (...args) => {
const key = generateKey(args);
if (cache.has(key)) {
const value = cache.get(key);
console.log('from cache:', value.res);
value.count += 1;
return value.res;
}
const res = fn(...args);
console.log('Calculated:', res);
if (cache.size > max) {
let [deleted, { count: num }] = cache.entries().next().value;
cache.forEach((value, keys) => {
const count = value.count;
if (num >= count) {
num = count;
deleted = keys;
}
});
console.log('deleted: ', deleted);
cache.delete(deleted);
}
cache.set(key, { res, count: 1 });
return res;
};
};
const sum = (a, b) => a + b;
const f1 = countMemoize(sum, 3);
f1(1, 2);
f1(1, 2);
f1(1, 2);
f1(2, 4);
f1(2, 4);
f1(3, 4);
f1(4, 4);
f1(4, 4);
f1(3, 4);
f1(4, 4);
f1(4, 4);
f1(5, 4);
f1(5, 4);