LRU Cache LeetCode solution in JavaScript

1
/**
2
* @param {number} capacity
3
*/
4
var LRUCache = function (capacity) {
5
this.capacity = capacity;
6
this.cache = new Map();
7
};
8

9
/**
10
* @param {number} key
11
* @return {number}
12
*/
13
LRUCache.prototype.get = function (key) {
14
if (!this.cache.has(key)) {
15
return -1;
16
}
17

18
let val = this.cache.get(key);
19
this.cache.delete(key);
20
this.cache.set(key, val);
21
return val;
22
};
23

24
/**
25
* @param {number} key
26
* @param {number} value
27
* @return {void}
28
*/
29
LRUCache.prototype.put = function (key, value) {
30
if (this.cache.has(key)) {
31
this.cache.delete(key);
32
} else {
33
if (this.cache.size >= this.capacity) {
34
let [lastElm] = this.cache.keys();
35
this.cache.delete(lastElm);
36
}
37
}
38
this.cache.set(key, value);
39
};
40

41
/**
42
* Your LRUCache object will be instantiated and called as such:
43
* var obj = new LRUCache(capacity)
44
* var param_1 = obj.get(key)
45
* obj.put(key,value)
46
*/

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0