Skip to content

Commit

Permalink
fix
Browse files Browse the repository at this point in the history
  • Loading branch information
Galcarmi committed May 7, 2024
1 parent 86fd6ca commit 6b55c49
Showing 1 changed file with 45 additions and 0 deletions.
45 changes: 45 additions & 0 deletions lib/LRUCache.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
class LRUCache {
/**
* @param {number} maxSize maxSize
*/
constructor(maxSize) {
this._maxSize = maxSize;
/** @type {string[]} */
this._doublyQueue = [];
this._cacheMap = new Map();
}

/**
* @param {string} item item
*/
get(item) {
if (this._cacheMap.has(item)) {
const itemData = this._doublyQueue.splice(
this._doublyQueue.indexOf(item),
1
);
this._doublyQueue.unshift(item);

if (itemData.length > 0) {
this._cacheMap.set(item, itemData[0]);
}
}
}

/**
* @param {any} item item
* @param {any} itemData itemData
*/
set(item, itemData) {
if (this._doublyQueue.length === this._maxSize) {
const last = this._doublyQueue[this._doublyQueue.length - 1];
this._doublyQueue.pop();
this._cacheMap.delete(last);
}

this._doublyQueue.unshift(item);
this._cacheMap.set(item, itemData);
}
}

module.exports = LRUCache;

0 comments on commit 6b55c49

Please sign in to comment.