/
index.js
55 lines (55 loc) · 1.52 KB
/
index.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
48
49
50
51
52
53
54
55
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Cache = void 0;
// Lazy Cache based on Map
class Cache {
// factory for creating entries
constructor(factoryFunction, maxSize = Infinity) {
this.data = new Map();
this.factoryFunction = factoryFunction;
this.maxSize = maxSize;
}
// get data size
get size() {
return this.data.size;
}
// creates a string from args
createKey(...args) {
return args.length > 1 ? args.join(",") : args[0];
}
// wrapped factory function
create(...args) {
return this.factoryFunction.apply(this, args);
}
// has entry at [args]
hasKey(...args) {
return this.has(this.createKey.apply(this, args));
}
// has entry at [args]
has(key) {
return this.data.has(key);
}
// get with key
get(...args) {
const key = this.createKey.apply(this, args);
if (this.hasKey(key)) {
return this.data.get(key);
}
while (this.data.size >= this.maxSize) {
const [keyToRemove] = this.data.entries().next().value;
this.deleteKey(keyToRemove);
}
const value = this.create.apply(this, args);
this.data.set(key, value);
return value;
}
// delete entry at [args]
deleteKey(...args) {
return this.delete(this.createKey.apply(this, args));
}
// delete entry at [args]
delete(key) {
return this.data.delete(key);
}
}
exports.Cache = Cache;