-
Notifications
You must be signed in to change notification settings - Fork 0
/
mru-cache.js
49 lines (40 loc) · 1.12 KB
/
mru-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
45
46
47
48
49
class MRUCache {
constructor(capacity) {
this.capacity = capacity;
this.cache = new Map();
this.accessOrder = [];
}
get(key) {
if (this.cache.has(key)) {
this.updateAccessOrder(key);
return this.cache.get(key);
}
return -1;
}
put(key, value) {
if (this.capacity === 0) return;
if (this.cache.has(key)) {
this.cache.set(key, value);
this.updateAccessOrder(key);
} else {
if (this.cache.size >= this.capacity) {
const mruKey = this.accessOrder.pop();
this.cache.delete(mruKey);
}
this.cache.set(key, value);
this.accessOrder.unshift(key);
}
}
updateAccessOrder(key) {
const index = this.accessOrder.indexOf(key);
this.accessOrder.splice(index, 1);
this.accessOrder.unshift(key);
}
}
const mruCache = new MRUCache(3);
mruCache.put(1, "One");
mruCache.put(2, "Two");
mruCache.put(3, "Three");
console.log(mruCache.get(2));
mruCache.put(4, "Four");
console.log(mruCache.get(1));