Class LRUCache<T>

Class representing an LRU (Least Recently Used) Cache. The cache evicts the least recently used items when the maximum capacity is reached.

const cache = new LRUCache<number>(2); // Cache with capacity for 2 items
cache.put(1, 100);
cache.put(2, 200);
console.log(cache.get(1)); // Outputs: 100
cache.put(3, 300); // Evicts key 2 as it is the least recently used
console.log(cache.get(2)); // Outputs: null

Type Parameters

  • T

    The type of values stored in the cache.

Constructors

Methods

Constructors

Methods

  • Retrieves the value associated with the specified key. If the key exists, the node is moved to the head (most recently used).

    Parameters

    • key: number

      The key to look up.

    Returns T

    • The value associated with the key, or null if not found.
  • Inserts or updates the value associated with the specified key. If the key exists, it updates the value and moves the node to the head. If the key is new, it adds the key-value pair and evicts the LRU item if over capacity.

    Parameters

    • key: number

      The key to insert or update.

    • value: T

      The value to associate with the key.

    Returns void