-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0146-lru-cache.js
More file actions
34 lines (29 loc) · 795 Bytes
/
0146-lru-cache.js
File metadata and controls
34 lines (29 loc) · 795 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
/**
* Lru Cache
* Time Complexity: O(1)
* Space Complexity: O(N)
*/
var LRUCache = function (capacity) {
this.cacheLimit = capacity;
this.dataStore = new Map();
};
LRUCache.prototype.get = function (key) {
if (!this.dataStore.has(key)) {
return -1;
}
const retrievedCacheValue = this.dataStore.get(key);
this.dataStore.delete(key);
this.dataStore.set(key, retrievedCacheValue);
return retrievedCacheValue;
};
LRUCache.prototype.put = function (key, value) {
if (this.dataStore.has(key)) {
this.dataStore.delete(key);
}
this.dataStore.set(key, value);
const currentStorageSize = this.dataStore.size;
if (currentStorageSize > this.cacheLimit) {
const leastUsedKey = this.dataStore.keys().next().value;
this.dataStore.delete(leastUsedKey);
}
};