Class LRUCache<K, V>

Source
Expand description

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: 1
cache.put('d', 4); // Evicts key 'b' as it is the least recently used
console.log(cache.has('b')); // Outputs: false

Constructors§

Source§

new LRUCache<K, V>(capacity: number): LRUCache<K, V>

Creates an instance of LRUCache.

throws

when the provided capacity is not a positive number.

complexity

O(1)

Accessors§

Source§

get capacity(): number

Returns the maximum capacity of the cache.

complexity

O(1)

Source§

get size(): number

Returns the current number of items in the cache.

complexity

O(1)

Methods§

Source§

clear(): void

Removes all items from the cache.

complexity

O(N), where N is the number of items in the cache.

Source§

delete(key: K): boolean

Removes an item from the cache.

complexity

O(1) on average.

Source§

get(key: K): undefined | V

Retrieves the value associated with the given key from the cache. This operation marks the item as recently used.

complexity

O(1) on average.

Source§

has(key: K): boolean

Checks if a key exists in the cache without updating its usage.

complexity

O(1) on average.

Source§

put(key: K, value: V): void

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.

complexity

O(1) on average.