-
-
Notifications
You must be signed in to change notification settings - Fork 24
Expand file tree
/
Copy path3-cacheSize.js
More file actions
37 lines (32 loc) · 816 Bytes
/
3-cacheSize.js
File metadata and controls
37 lines (32 loc) · 816 Bytes
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
'use strict';
const argKey = (x) => x.toString() + ':' + typeof x;
const generateKey = (args) => args.map(argKey).join('|');
const memoize = (fn, length) => {
const cache = new Map();
return (...args) => {
const key = generateKey(args);
console.log(`${fn.name}(${key}) call`);
if (cache.has(key)) return cache.get(key);
console.log(`max(${key}) calculate`);
const res = fn(...args);
if (cache.size >= length) {
const firstKey = cache.keys().next().value;
console.log('Delete key:', firstKey);
cache.delete(firstKey);
}
cache.set(key, res);
return res;
};
};
// Usage
const max = (a, b) => (a > b ? a : b);
const mMax = memoize(max, 3);
mMax(10, 8);
mMax(10, 8);
mMax(1, 15);
mMax(12, 3);
mMax(15, 2);
mMax(1, 15);
mMax(10, 8);
mMax(0, 0);
mMax(0, 0);