-
Notifications
You must be signed in to change notification settings - Fork 921
Expand file tree
/
Copy pathlru-cache.js
More file actions
47 lines (41 loc) · 878 Bytes
/
lru-cache.js
File metadata and controls
47 lines (41 loc) · 878 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
36
37
38
39
40
41
42
43
44
45
46
47
/**
* Least Recently Used (LRU) cache.
* (ordered) Map: O(1)
* @param {number} capacity - Number of items to hold.
*/
class LRUCache {
constructor(capacity) {
this.map = new Map();
this.capacity = capacity;
}
get(key) {
const value = this.map.get(key);
if (value) {
this.moveToTop(key);
return value;
}
return -1;
}
put(key, value) {
this.map.set(key, value);
this.rotate(key);
}
rotate(key) {
this.moveToTop(key);
while (this.map.size > this.capacity) {
const it = this.map.keys(); // keys are in insertion order.
this.map.delete(it.next().value);
}
}
moveToTop(key) {
if (this.map.has(key)) {
const value = this.map.get(key);
this.map.delete(key);
this.map.set(key, value);
}
}
get size() {
return this.map.size;
}
}
module.exports = LRUCache;