Skip to content

Commit 6b55c49

Browse files
committed
fix
1 parent 86fd6ca commit 6b55c49

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed

lib/LRUCache.js

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
class LRUCache {
2+
/**
3+
* @param {number} maxSize maxSize
4+
*/
5+
constructor(maxSize) {
6+
this._maxSize = maxSize;
7+
/** @type {string[]} */
8+
this._doublyQueue = [];
9+
this._cacheMap = new Map();
10+
}
11+
12+
/**
13+
* @param {string} item item
14+
*/
15+
get(item) {
16+
if (this._cacheMap.has(item)) {
17+
const itemData = this._doublyQueue.splice(
18+
this._doublyQueue.indexOf(item),
19+
1
20+
);
21+
this._doublyQueue.unshift(item);
22+
23+
if (itemData.length > 0) {
24+
this._cacheMap.set(item, itemData[0]);
25+
}
26+
}
27+
}
28+
29+
/**
30+
* @param {any} item item
31+
* @param {any} itemData itemData
32+
*/
33+
set(item, itemData) {
34+
if (this._doublyQueue.length === this._maxSize) {
35+
const last = this._doublyQueue[this._doublyQueue.length - 1];
36+
this._doublyQueue.pop();
37+
this._cacheMap.delete(last);
38+
}
39+
40+
this._doublyQueue.unshift(item);
41+
this._cacheMap.set(item, itemData);
42+
}
43+
}
44+
45+
module.exports = LRUCache;

0 commit comments

Comments
 (0)