-
-
Notifications
You must be signed in to change notification settings - Fork 26
/
Copy path8-timer.js
47 lines (38 loc) · 893 Bytes
/
8-timer.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
40
41
42
43
44
45
46
47
'use strict';
const memoize = (fn, msec = 100) => {
let cache = {};
let timer = setTimeout(() => {
console.log('Cache cleaned');
timer = null;
cache = {};
}, msec);
const setTimer = msec => {
timer = setTimeout(() => {
console.log('Cache cleaned');
timer = null;
cache = {};
}, msec);
};
const generateKey = (...args) => args.join('|');
return (...args) => {
if (!timer) setTimer(msec);
const key = generateKey(...args);
if (cache[key]) {
console.log(`From cache: ${args} = ${cache[key]}`);
return cache[key];
}
console.log(`Calculate: ${args} = ${fn(...args)}`);
const res = fn(...args);
cache[key] = res;
console.log(cache);
return res;
};
};
const sum = (a, b) => a + b;
const sumM = memoize(sum, 2000);
//USAGE
sumM(1, 2);
sumM(1, 2);
setTimeout(() => {
sumM(1, 2);
}, 2500);