diff --git a/lib/LRUCache.js b/lib/LRUCache.js new file mode 100644 index 00000000..6bf4ff01 --- /dev/null +++ b/lib/LRUCache.js @@ -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; diff --git a/lib/util/path.js b/lib/util/path.js index 4a65c6e3..343f5e9a 100644 --- a/lib/util/path.js +++ b/lib/util/path.js @@ -6,6 +6,7 @@ "use strict"; const path = require("path"); +const { LRUCache } = require("lru-cache"); const CHAR_HASH = "#".charCodeAt(0); const CHAR_SLASH = "/".charCodeAt(0); @@ -170,8 +171,8 @@ const join = (rootPath, request) => { }; exports.join = join; -/** @type {Map>} */ -const joinCache = new Map(); +/** @type {LRUCache>} */ +const joinCache = new LRUCache({ max: 500 }); /** * @param {string} rootPath the root path diff --git a/package.json b/package.json index f9f32020..c849b42d 100644 --- a/package.json +++ b/package.json @@ -14,6 +14,7 @@ }, "dependencies": { "graceful-fs": "^4.2.4", + "lru-cache": "^10.2.2", "tapable": "^2.2.0" }, "license": "MIT", diff --git a/yarn.lock b/yarn.lock index 7e0355bd..2f8addd9 100644 --- a/yarn.lock +++ b/yarn.lock @@ -3063,6 +3063,11 @@ log-update@^4.0.0: slice-ansi "^4.0.0" wrap-ansi "^6.2.0" +lru-cache@^10.2.2: + version "10.2.2" + resolved "https://registry.npmjs.org/lru-cache/-/lru-cache-10.2.2.tgz#48206bc114c1252940c41b25b41af5b545aca878" + integrity sha512-9hp3Vp2/hFQUiIwKo8XCeFVnrg8Pk3TYNPIR7tJADKi5YfcF7vEaK7avFHTlSy3kOKYaJQaalfEo6YuXdceBOQ== + lru-cache@^5.1.1: version "5.1.1" resolved "https://registry.yarnpkg.com/lru-cache/-/lru-cache-5.1.1.tgz#1da27e6710271947695daf6848e847f01d84b920"