A Least Recently Used (LRU) Cache implementation.
import { LRUCache } from '../src/index.js';const cache = new LRUCache<string, number>(3);cache.put('a', 1);cache.put('b', 2);cache.put('c', 3);console.log(cache.get('a')); // Outputs: 1cache.put('d', 4); // Evicts key 'b' as it is the least recently usedconsole.log(cache.has('b')); // Outputs: false Copy
import { LRUCache } from '../src/index.js';const cache = new LRUCache<string, number>(3);cache.put('a', 1);cache.put('b', 2);cache.put('c', 3);console.log(cache.get('a')); // Outputs: 1cache.put('d', 4); // Evicts key 'b' as it is the least recently usedconsole.log(cache.has('b')); // Outputs: false
Creates an instance of LRUCache.
when the provided capacity is not a positive number.
O(1)
Returns the maximum capacity of the cache.
Returns the current number of items in the cache.
Removes all items from the cache.
O(N), where N is the number of items in the cache.
Removes an item from the cache.
O(1) on average.
Retrieves the value associated with the given key from the cache. This operation marks the item as recently used.
Checks if a key exists in the cache without updating its usage.
Adds or updates a key-value pair in the cache. This operation marks the item as recently used. If adding a new item exceeds the cache's capacity, the least recently used item is evicted.
A Least Recently Used (LRU) Cache implementation.