-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathcache.js
44 lines (39 loc) · 898 Bytes
/
cache.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
const DEFAULT_MAX_CACHE_SIZE = 1024 * 1024 * 10;
class Cache {
constructor(options = {}) {
this.MAX_CACHE_SIZE = options.maxCacheSize || DEFAULT_MAX_CACHE_SIZE;
this.map = new Map();
this.size = 0;
this.fifo = [];
}
append(url, data) {
let size;
if (typeof data === 'string') {
size = data.length * 2;
} else {
size = data.length;
}
while (this.size + size > this.MAX_CACHE_SIZE) {
const url = this.fifo.shift();
const entry = this.map.get(url);
this.size -= entry.size;
this.map.delete(url);
}
this.map.set(url, {url, data, size});
this.size += size;
this.fifo.push(url);
}
get(url) {
const entry = this.map.get(url);
if (entry) {
return entry.data;
}
return null;
}
clear() {
this.map.clear();
this.size = 0;
this.fifo = [];
}
}
module.exports = Cache;