UNPKG

mem100x

Version:

⚡ The FASTEST MCP memory server ever built - 66k+ entities/sec with intelligent context detection

143 lines 3.67 kB
"use strict"; /** * High-Performance LRU Cache with O(1) operations * Uses doubly-linked list and hash map for optimal performance */ Object.defineProperty(exports, "__esModule", { value: true }); exports.LRUCache = void 0; class ListNode { key; value; prev; next; constructor(key, value, prev = null, next = null) { this.key = key; this.value = value; this.prev = prev; this.next = next; } } class LRUCache { maxSize; cache; head = null; tail = null; size = 0; // Performance metrics hits = 0; misses = 0; constructor(maxSize = 1000) { this.maxSize = maxSize; this.cache = new Map(); } get(key) { const node = this.cache.get(key); if (node) { // Move to front (most recently used) this.moveToFront(node); this.hits++; return node.value; } this.misses++; return undefined; } set(key, value) { const existingNode = this.cache.get(key); if (existingNode) { // Update existing node existingNode.value = value; this.moveToFront(existingNode); return; } // Create new node const newNode = new ListNode(key, value); this.cache.set(key, newNode); // Add to front of list if (!this.head) { this.head = this.tail = newNode; } else { newNode.next = this.head; this.head.prev = newNode; this.head = newNode; } this.size++; // Evict if necessary if (this.size > this.maxSize) { this.evictLRU(); } } moveToFront(node) { // Already at front if (node === this.head) return; // Remove from current position if (node.prev) node.prev.next = node.next; if (node.next) node.next.prev = node.prev; if (node === this.tail) this.tail = node.prev; // Move to front node.prev = null; node.next = this.head; if (this.head) this.head.prev = node; this.head = node; } evictLRU() { if (!this.tail) return; // Remove from map this.cache.delete(this.tail.key); // Remove from list if (this.tail.prev) { this.tail = this.tail.prev; this.tail.next = null; } else { // Only one node this.head = this.tail = null; } this.size--; } has(key) { return this.cache.has(key); } delete(key) { const node = this.cache.get(key); if (!node) return false; // Remove from map this.cache.delete(key); // Remove from list if (node.prev) node.prev.next = node.next; if (node.next) node.next.prev = node.prev; if (node === this.head) this.head = node.next; if (node === this.tail) this.tail = node.prev; this.size--; return true; } clear() { this.cache.clear(); this.head = this.tail = null; this.size = 0; this.hits = 0; this.misses = 0; } getStats() { const total = this.hits + this.misses; return { hits: this.hits, misses: this.misses, hitRate: total > 0 ? this.hits / total : 0, size: this.size }; } } exports.LRUCache = LRUCache; //# sourceMappingURL=lru-cache.js.map