UNPKG

lrufy

Version:

A feature-rich LRU cache implementation with TTL support, custom sizing, and event hooks

104 lines (103 loc) 2.48 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.DoublyLinkedList = exports.Node = void 0; /** * Represents a node in a doubly linked list */ class Node { /** * Creates a new node * @param key - The key associated with this node * @param value - The value stored in this node */ constructor(key, value) { this.prev = null; this.next = null; this.size = 0; this.expiry = null; this.key = key; this.value = value; } } exports.Node = Node; /** * A doubly linked list implementation to track LRU order */ class DoublyLinkedList { constructor() { this.head = null; this.tail = null; this.length = 0; } /** * Adds a node to the front of the list (most recently used) * @param node - The node to add * @returns The added node */ addToFront(node) { if (!this.head) { this.head = node; this.tail = node; } else { node.next = this.head; this.head.prev = node; this.head = node; } this.length++; return node; } /** * Removes a node from the list * @param node - The node to remove * @returns The removed node */ remove(node) { if (node.prev) { node.prev.next = node.next; } else { this.head = node.next; } if (node.next) { node.next.prev = node.prev; } else { this.tail = node.prev; } node.prev = null; node.next = null; this.length--; return node; } /** * Moves a node to the front of the list (marks as recently used) * @param node - The node to move to the front * @returns The moved node */ moveToFront(node) { if (this.head === node) { return node; } this.remove(node); return this.addToFront(node); } /** * Removes the least recently used node (from the tail) * @returns The removed node or null if the list is empty */ removeTail() { if (!this.tail) return null; return this.remove(this.tail); } /** * Clears the linked list */ clear() { this.head = null; this.tail = null; this.length = 0; } } exports.DoublyLinkedList = DoublyLinkedList;