-
Notifications
You must be signed in to change notification settings - Fork 931
/
Copy pathlru-cache-1.js
50 lines (46 loc) · 1014 Bytes
/
lru-cache-1.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
/**
* Least Recently Used (LRU) cache.
* Map + Array: O(n)
* @param {number} capacity - Number of items to hold.
*/
const LRUCache = function (capacity) {
this.map = new Map();
this.capacity = capacity;
this.cache = [];
};
/**
* @param {number} key
* @return {number}
*/
LRUCache.prototype.get = function (key) {
const value = this.map.get(key);
if (value) {
this.moveToTop(key);
return value;
}
return -1;
};
/**
* @param {number} key
* @param {number} value
* @return {void}
*/
LRUCache.prototype.put = function (key, value) {
this.map.set(key, value);
this.rotate(key);
};
LRUCache.prototype.rotate = function (key) {
this.moveToTop(key);
while (this.cache.length > this.capacity) {
const keyToDelete = this.cache.shift();
this.map.delete(keyToDelete);
// console.log({keyToDelete})
}
};
LRUCache.prototype.moveToTop = function (key) {
const index = this.cache.indexOf(key);
if (index > -1) {
this.cache.splice(index, 1);
}
this.cache.push(key);
};