-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy path0146_LRUCache.js
46 lines (43 loc) · 1 KB
/
0146_LRUCache.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
/**
* @param {number} capacity
*/
var LRUCache = function(capacity) {
this.capacity = capacity;
this.map = new Map();
};
/**
* @param {number} key
* @return {number}
*/
LRUCache.prototype.get = function(key) {
let val = this.map.get(key)
if(val == undefined){return -1;}
//Map has sorted order. FIFO.
this.map.delete(key);
//we get value and push it to the back;
this.map.set(key,val);
return val;
};
/**
* @param {number} key
* @param {number} value
* @return {void}
*/
LRUCache.prototype.put = function(key, value) {
//remove value if exists.
if(this.map.has(key)){
this.map.delete(key)
}
this.map.set(key,value);
let keys = this.map.keys();
while(this.map.size > this.capacity){
//remove Least Recently Used elements
this.map.delete(keys.next().value)
}
};
/**
* Your LRUCache object will be instantiated and called as such:
* var obj = new LRUCache(capacity)
* var param_1 = obj.get(key)
* obj.put(key,value)
*/