-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcreateLRUCacheClass.js
More file actions
74 lines (61 loc) · 1.42 KB
/
Copy pathcreateLRUCacheClass.js
File metadata and controls
74 lines (61 loc) · 1.42 KB
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
66
67
68
69
70
71
72
73
74
class LRUCache {
constructor(capacity) {
if (capacity <= 0) {
throw new Error("Capacity must be greater than 0");
}
this.capacity = capacity;
this.cache = new Map();
}
get(key) {
if (!this.cache.has(key)) {
return null;
}
const value = this.cache.get(key);
// Move the key to the end to mark it as recently used
this.cache.delete(key);
this.cache.set(key, value);
return value;
}
add(key, value) {
if (this.cache.has(key)) {
this.cache.delete(key);
} else if (this.cache.size >= this.capacity) {
// Evict the least recently used item
const lruKey = this.cache.keys().next().value;
this.cache.delete(lruKey);
}
this.cache.set(key, value);
}
update(key, value) {
if (!this.cache.has(key)) {
throw new Error(`Cannot update non-existing key: ${key}`);
}
this.cache.delete(key);
this.cache.set(key, value);
}
remove(key) {
this.cache.delete(key);
}
keys() {
return Array.from(this.cache.keys());
}
values() {
return Array.from(this.cache.values());
}
size() {
return this.cache.size;
}
clear() {
this.cache.clear();
}
}
const cache = new LRUCache(3);
cache.add('a', 1);
cache.add('b', 2);
cache.add('c', 3);
// Access 'a' to mark it as recently used
cache.get('a');
// Add 'd', which should evict 'b'
cache.add('d', 4);
console.log(cache.keys());
// Expected: ['c', 'a', 'd']