-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathLRUCache.js
51 lines (44 loc) · 935 Bytes
/
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
47
48
49
50
51
/**
* @param {number} capacity
*/
const 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)) {
return -1
}
const value = this.map.get(key)
this.map.delete(key)
this.map.set(key, value)
return value
}
/**
* @param {number} key
* @param {number} value
* @return {void}
*/
LRUCache.prototype.put = function (key, value) {
if (this.map.has(key)) {
this.map.delete(key)
this.map.set(key, value)
return
}
if (this.map.size >= this.capacity) {
const deleteKey = this.map.keys().next().value
this.map.delete(deleteKey)
}
this.map.set(key, 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)
*/
module.exports = LRUCache