-
-
Notifications
You must be signed in to change notification settings - Fork 4.2k
Expand file tree
/
Copy pathcache.js
More file actions
35 lines (35 loc) · 712 Bytes
/
cache.js
File metadata and controls
35 lines (35 loc) · 712 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
export default class Cache {
constructor(limit, func, store) {
this.limit = limit;
this.func = func;
this.store = store;
this.size = 0;
this.misses = 0;
this.hits = 0;
this.store = store || new Map();
}
get(key) {
let value = this.store.get(key);
if (this.store.has(key)) {
this.hits++;
return this.store.get(key);
} else {
this.misses++;
value = this.set(key, this.func(key));
}
return value;
}
set(key, value) {
if (this.limit > this.size) {
this.size++;
this.store.set(key, value);
}
return value;
}
purge() {
this.store.clear();
this.size = 0;
this.hits = 0;
this.misses = 0;
}
}