-
-
Notifications
You must be signed in to change notification settings - Fork 24
Expand file tree
/
Copy path8-timeout.js
More file actions
77 lines (64 loc) · 1.7 KB
/
8-timeout.js
File metadata and controls
77 lines (64 loc) · 1.7 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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
'use strict';
const memoize = (fn, msec = 100) => {
const cache = {};
let timer = null;
const hasKey = (key) => Object.keys(cache).includes(key);
const generateKey = (args) => {
let key = '';
for (const arg of args)
key += `${arg}~${typeof arg}|`;
return key;
};
const throwGarbage = () => {
const cleaningTime = new Date();
const removingTime = cleaningTime - msec;
const toDelete = Object.keys(cache)
.filter(key => cache[key].lastUse >= removingTime);
for (const key in cache) {
if (toDelete.includes(key)) {
console.log(`${key} deleted.`);
delete cache[key];
}
if (Object.keys(cache).length === 0) {
console.log('Cache is empty');
clearInterval(timer);
timer = null;
}
}
};
const setTimer = (msec) => {
const timer = setInterval(() => throwGarbage(), msec);
return timer;
};
timer = setTimer(msec);
const func = (...args) => {
if (!timer) timer = setTimer(msec);
const key = generateKey(args);
if (hasKey(key)) {
console.log(`From cache: ${args} = ${cache[key].value}`);
cache[key].lastUse = new Date();
console.log(cache);
return cache[key].value;
}
console.log(`Calculate: ${args} = ${fn(...args)}`);
const res = fn(...args);
if (res !== undefined)
cache[key] = { value: res, lastUse: new Date() };
console.log(cache);
return res;
};
return func;
};
const sum = (a, b) => a + b;
const sumM = memoize(sum, 250);
//USAGE
sumM(1, -1);
sumM(2, -1);
setTimeout(() => {
sumM(1, -1);
setTimeout(() => sumM(2, -1), 100);
setTimeout(() => {
sumM(2, 3);
setTimeout(() => sumM(3, 4), 1000);
}, 500);
}, 200);