-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathindex.js
65 lines (57 loc) · 1.38 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
56
57
58
59
60
61
62
63
64
65
class FixedSizeMap {
/**
* The max number of keys this cache can hold
* @param {number} size
*/
constructor(size) {
if (typeof size !== 'number' || size < 1 || !Number.isInteger(size)) {
throw new Error('Cache size must be an integer greater than 0');
}
this.map = new Map();
this.keys = new Array(size);
this.currIndex = 0;
}
/**
* Adds a key and pairs it with a value
* If this is already at maximum occupation, this will remove the oldest element.
* @param {any} key
* @param {any} value
*/
add(key, value) {
if (this.map.has(key)) {
this.map.set(key, value);
return;
}
if (this.keys[this.currIndex] != null) {
this.map.delete(this.keys[this.currIndex]);
}
this.keys[this.currIndex] = key;
this.currIndex = (this.currIndex + 1) % this.keys.length;
this.map.set(key, value);
}
/**
* Checks if this cache contains a key
* @param {any} key
*/
contains(key) {
return this.map.has(key);
}
/**
* Retrieves a value from this cache corresponding to the specified key
* @param {any} key
*/
get(key) {
return this.map.get(key);
}
/**
* Removed the key value entry from this cache corresponding to the specified key
* @param {any} key
*/
remove(key) {
this.map.delete(key);
}
clear() {
this.map.clear();
}
}
module.exports = FixedSizeMap;