sussy-util
Version:
Util package made by me
79 lines (78 loc) • 2.83 kB
TypeScript
import Optional from "./Optional";
/**
* A Least Recently Used (LRU) Cache implementation with a fixed capacity.
*
* @template Key - The type of keys stored in the cache.
* @template Value - The type of values stored in the cache.
*/
export default class LRUCache<Key, Value> {
private readonly capacity;
private cache;
private usageOrder;
private objectPool;
private evictionCallback;
/**
* Create an LRUCache instance with a specified capacity.
*
* @param {number} capacity - The maximum number of entries the cache can hold.
*/
constructor(capacity: number);
/**
* Retrieve a value from the cache based on the provided key.
* Moves the accessed item to the front of the usage order.
*
* @param {Key} key - The key for the desired value.
* @returns {Value | undefined} - The value associated with the key, or undefined if not found.
*/
get(key: Key): Optional<Value>;
/**
* Add a key-value pair to the cache. If the cache exceeds capacity, the least recently used item is evicted.
* Moves the added or accessed item to the front of the usage order.
*
* @param {Key} key - The key for the new item.
* @param {Value} value - The value associated with the key.
*/
put(key: Key, value: Value): void;
/**
* Add multiple key-value pairs to the cache. If the cache exceeds capacity, the least recently used items are evicted.
* Moves the added or accessed items to the front of the usage order.
*
* @param {[Key, Value][]} entries - An array of key-value pairs to add to the cache.
*/
putAll(entries: [Key, Value][]): void;
/**
* Clear all entries from the cache.
*/
clear(): void;
/**
* Get an array of all keys currently in the cache.
*
* @returns {Key[]} - An array of keys in the cache.
*/
getAllKeys(): Key[];
/**
* Get an array of all values currently in the cache.
*
* @returns {Value[]} - An array of values in the cache.
*/
getAllValues(): Value[];
/**
* Get a generator yielding all entries (key-value pairs) in the cache.
*
* @yields {[Key, Value]} - A key-value pair from the cache.
*/
entries(): Generator<[Key, Value]>;
/**
* Set a callback function to be called when an item is evicted from the cache.
*
* @param {(key: Key, value: Value) => void} callback - The callback function.
*/
setEvictionCallback(callback: (key: Key, value: Value) => void): void;
/**
* Remove an item from the cache based on the provided key.
*
* @param {Key} key - The key of the item to remove.
* @returns {boolean} - True if the item was removed, false if the key was not found.
*/
remove(key: Key): boolean;
}