UNPKG

@homeofthings/node-utils

Version:

HomeOfThings - Node Utils: various utilities and common types

58 lines 1.55 kB
"use strict"; /* eslint-disable @typescript-eslint/no-unused-vars */ Object.defineProperty(exports, "__esModule", { value: true }); exports.LruCache = void 0; class LruCache { _maxEntries; // NOTE: javascript Map remembers the original insertion order _map = new Map(); get maxEntries() { return this._maxEntries; } set maxEntries(newMaxEntries) { this._maxEntries = Math.max(newMaxEntries, 0); this.resize(this._maxEntries); } get size() { return this._map.size; } constructor(_maxEntries = 20) { this._maxEntries = _maxEntries; } get(key) { let item = undefined; if (this._map.has(key)) { // mark item as least recently used item = this._map.get(key); this._map.delete(key); this._map.set(key, item); } return item; } set(key, item) { if (!this.delete(key)) { this.resize(this._maxEntries - 1); } this.onInsert(item); this._map.set(key, item); } has(key) { return this._map.has(key); } delete(key) { const item = this._map.get(key); if (item) { this.onDelete(item); } return this._map.delete(key); } onInsert(_item) { } onDelete(_item) { } resize(newSize) { while (this._map.size > newSize) { this.delete(this._map.keys().next().value); } } } exports.LruCache = LruCache; //# sourceMappingURL=lru-cache.js.map