-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
136 lines (113 loc) · 2.64 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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
/**
* Doubly Linked List Implementation
*/
class Node {
constructor(key, value, next = null, prev = null) {
this.key = key;
this.value = value;
this.next = next;
this.prev = prev;
}
}
/**
* @param {number} capacity
*/
var LRUCache = function(capacity) {
this.size = 0;
this.limit = capacity;
this.cache = {};
this.head = null;
this.tail = null;
};
/**
* @param {number} key
* @return {number}
*/
LRUCache.prototype.get = function(key) {
if(this.cache[key]){
const value = this.cache[key].value;
// node removed from it's position and cache
this.remove(key)
// this.size--;
// write node again to the head of LinkedList to make it most recently used
this.put(key, value);
return value;
}
return -1;
};
/**
* @param {number} key
* @param {number} value
* @return {void}
*/
LRUCache.prototype.put = function(key, value) {
if(!this.head){
this.head = this.tail = new Node(key, value);
}else{
const node = new Node(key, value, this.head);
this.head.prev = node;
this.head = node;
}
//Update the cache map
if(this.cache[key]){
this.remove(key);
this.cache[key] = this.head;
this.size++;
}else{
this.ensureLimit();
this.cache[key] = this.head;
this.size++;
}
};
LRUCache.prototype.ensureLimit = function() {
if(this.size == this.limit){
this.remove(this.tail.key);
}
};
LRUCache.prototype.remove = function(key) {
const node = this.cache[key];
if(node == undefined) return;
// console.log(node)
if(node.prev !== null){
node.prev.next = node.next;
}else{
this.head = node.next;
}
if(node.next !== null){
node.next.prev = node.prev;
}else{
this.tail = node.prev
}
delete this.cache[key];
this.size--;
};
LRUCache.prototype.getCache = function() {
let contents = {};
for(let i in this.cache){
contents[i] = this.cache[i].value;
}
return contents;
}
LRUCache.prototype.getKeysOfValue = function(val){
let keys = [];
for(let i in this.cache){
if(this.cache[i].value === val)
keys.push(this.cache[i].key)
}
return keys;
}
LRUCache.prototype.getAllValues = function(){
let values = [];
for(let i in this.cache){
values.push(this.cache[i].value)
}
return values;
}
LRUCache.prototype.getAllKeys = function(){
let keys = [];
for(let i in this.cache){
keys.push(this.cache[i].key)
}
return keys;
}
module.exports = LRUCache;