-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path146.js
43 lines (40 loc) · 841 Bytes
/
146.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
/**
* @param {number} capacity
*/
var LRUCache = function (capacity) {
this.capacity = capacity;
this.map = new Map();
};
/**
* @param {number} key
* @return {number}
*/
LRUCache.prototype.get = function (key) {
if (this.map.has(key)) {
const value = this.map.get(key);
this.map.delete(key);
this.map.set(key, value);
return value;
} else {
return -1;
}
};
/**
* @param {number} key
* @param {number} value
* @return {void}
*/
LRUCache.prototype.put = function (key, value) {
if (this.map.has(key)) {
this.map.delete(key);
} else if (this.capacity === this.map.size) {
this.map.delete(this.map.keys().next().value);
}
this.map.set(key, value);
};
const cache = new LRUCache(2);
cache.put(1, 0);
cache.put(2, 2);
console.log(cache.get(1));
cache.put(3, 3);
console.log(cache.get(2));