LRUCache.js
912 Bytes
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
class LRUCache{
constructor(capacity){
this.capacity = capacity;
this.map = new Map();
}
get(key){
const value = this.map.get(key);
if(typeof value === "undefined"){
return -1;
}
this.map.delete(key);
this.map.set(key, value);
return value;
}
put(key, value){
let obj = {};
if(this.map.has(key)){
obj.key = key;
obj.value = this.map.get(key);
this.map.delete(key);
}
else{
obj.key = key;
obj.value = value;
}
this.map.set(key, value);
const keys = this.map.keys();
if(this.map.size > this.capacity){
obj.key = keys.next().value;
obj.value = this.map.get(obj.key);
this.map.delete(obj.key);
}
return obj;
}
}
module.exports = LRUCache;