-
Notifications
You must be signed in to change notification settings - Fork 22
Expand file tree
/
Copy pathLRUCache.js
More file actions
56 lines (42 loc) · 1.39 KB
/
LRUCache.js
File metadata and controls
56 lines (42 loc) · 1.39 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
/*
LRU Cache
Stores a limited number of items.- capacity.
When it reaches capacity and a new item is added, it evicts the least recently used item.
Accessing (reading/writing) an item makes it the most recently used.
JavaScript Map
O(1) read/write/delete by key
Insertion order tracking — first inserted = least recently used
*/
class LRUCache {
constructor(capacity = 2) {
this.capacity = capacity;
this.cache = new Map();
}
put(key, value){
if(this.cache.size === this.capacity) {
// Evict the least recently used item (first key)
const firstKey = this.cache.keys().next().value;
this.cache.delete(firstKey)
}
if(this.cache.has(key)){
this.cache.delete(key)
}
this.cache.set(key, value);
}
get(key) {
if(!this.cache.has(key)) return -1;
// if the item exists, move it to the top.
let value = this.cache.get(key);
this.cache.delete(key);
this.cache.set(key, value)
return value;
}
}
const LRU = new LRUCache(2);
LRU.put(1, 1); //{1 => 1}
LRU.put(2, 2); // {1 => 1, 2=> 2}
console.log(LRU.get(1)); // returns 1
console.log(LRU.get(2)); // returns 2
LRU.put(3, 3); // removes key 1 because it's least recently used { 2=>2 , 3 => 3}
console.log(LRU.get(3)); // returns 3
console.log(LRU.get(1)); // returns -1 (not found)