UNPKG

@splitsoftware/splitio-commons

Version:
43 lines (42 loc) 1.49 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.LRUCache = void 0; var LinkedList_1 = require("./LinkedList"); var LRUCache = /** @class */ (function () { function LRUCache(maxSize) { this.maxLen = maxSize || 1; this.items = new Map(); this.lru = new LinkedList_1.LinkedList(); } LRUCache.prototype.get = function (key) { var node = this.items.get(key); if (!node || !(node instanceof LinkedList_1.Node)) return; this.lru.unshiftNode(node); // Move to front return node.value.value; }; LRUCache.prototype.set = function (key, value) { var node = this.items.get(key); if (node) { if (!(node instanceof LinkedList_1.Node)) return false; this.lru.unshiftNode(node); // Move to front this.lru.head.value.value = value; // Update value } else { if (this.lru.length === this.maxLen) { // Remove last var last = this.lru.tail; if (!last) return false; this.items.delete(last.value.key); this.lru.removeNode(this.lru.tail); // Remove node } // @ts-ignore this.lru.unshift({ key: key, value: value }); // Push front this.items.set(key, this.lru.head); } return true; }; return LRUCache; }()); exports.LRUCache = LRUCache;