-
Notifications
You must be signed in to change notification settings - Fork 270
/
Copy pathindex.js
72 lines (62 loc) · 1.69 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
66
67
68
69
70
71
72
/*
Least recently used (LRU) - cache implementation
get(key) – Get the value (will always be positive) of the key if the key exists in the cache, otherwise return false.
Complexity: O(1)
set(key, value) – Set or insert the value if the key is not already present. When the cache reached its capacity, it should invalidate the least recently used item before inserting a new item.
Complexity: O(1)
*/
const DoublyLinkedList = require('../../_DataStructures_/DoublyLinkedList/index');
class LRUCache {
constructor(n) {
this.size = n;
this.map = new Map();
this.list = new DoublyLinkedList();
}
// this method will work in O(1)
set(key, value) {
const data = {
key,
value,
};
if (!this.map.has(key)) {
this.list.addAtBeginning(data);
this.map.set(key, this.list.head.next);
if (this.list.length() > this.size) {
const lastNode = this.list.tail.previous.data;
this.map.delete(lastNode.key);
this.list.removeAtEnd();
}
} else {
this.list.remove(this.map.get(key));
this.list.addAtBeginning(data);
this.map.set(key, this.list.head.next);
}
}
// this method will work in O(1)
get(key) {
if (this.map.has(key)) {
const node = this.map.get(key);
const { value } = node.data;
this.list.remove(node);
this.list.addAtBeginning({
key,
value,
});
this.map.set(key, this.list.head.next);
return value;
}
return false;
}
}
// const lru = new LRUCache(3);
// lru.set(1, 1);
// lru.set(2, 2);
// lru.set(3, 3);
// lru.set(4, 4);
// lru.set(5, 5);
// lru.set(2, 2);
// lru.get(5, 5);
// lru.list.display();
module.exports = {
LRUCache,
};