UNPKG

@phensley/cldr-utils

Version:
95 lines 2.63 kB
var DEFAULT_CAPACITY = 100; /** * Cache evicts the least-recently-used key when capacity is exceeded. */ var LRU = /** @class */ (function () { function LRU(capacity) { if (capacity === void 0) { capacity = DEFAULT_CAPACITY; } this.storage = new Map(); this.capacity = capacity; var root = {}; root.next = root; root.prev = root; this.root = root; } LRU.prototype.size = function () { return this.storage.size; }; LRU.prototype.get = function (key) { var n = this.storage.get(key); if (!n) { return undefined; } this.moveFront(n); return n.val; }; LRU.prototype.set = function (key, val) { if (this.capacity === 0) { return; } var n = this.storage.get(key); // Key already exists, so replace its value and bump it // to the front. Size does not change. if (n) { n.val = val; this.moveFront(n); return; } // The lru is full, so reuse the oldest node to keep the // total node allocation stable. if (this.storage.size === this.capacity) { var old = this.root.prev; if (old !== undefined) { this.storage.delete(old.key); this.storage.set(key, old); old.key = key; old.val = val; this.moveFront(old); } return; } // The lru is not full, so allocate a new node. n = { key: key, val: val }; this.storage.set(key, n); this.insert(n, this.root); }; LRU.prototype.toString = function () { var res = ''; var n = this.root.next; while (n && n !== this.root) { if (res.length > 0) { res += ' '; } res += n.key + "=" + n.val; n = n.next; } return res; }; LRU.prototype.moveFront = function (n) { this.insert(this.remove(n), this.root); }; LRU.prototype.insert = function (e, at) { var n = at.next; at.next = e; e.prev = at; e.next = n; if (n) { n.prev = e; } return e; }; LRU.prototype.remove = function (n) { if (n.prev) { n.prev.next = n.next; } if (n.next) { n.next.prev = n.prev; } n.prev = undefined; n.next = undefined; return n; }; return LRU; }()); export { LRU }; //# sourceMappingURL=lru.js.map