Curated collection of efficient data structures for JavaScript/TypeScript applications.
—
Pending
Does it follow best practices?
Impact
Pending
No eval scenarios have been run
Pending
The risk profile of this skill
LRU (Least Recently Used) caches with configurable capacity and efficient eviction policies for memory management.
Least Recently Used cache with configurable capacity and automatic eviction.
/**
* LRU Cache with configurable key/value types and capacity
* @param Keys Optional key array constructor for typed keys
* @param Values Optional value array constructor for typed values
* @param capacity Maximum number of items to store
*/
function LRUCache<K, V>(capacity: number): LRUCache<K, V>;
function LRUCache<K, V>(Keys: ArrayConstructor, Values: ArrayConstructor, capacity: number): LRUCache<K, V>;
interface LRUCache<K, V> {
/** Maximum number of items the cache can hold */
readonly capacity: number;
/** Current number of items in the cache */
readonly size: number;
/** Store key-value pair, evicts oldest if at capacity */
set(key: K, value: V): this;
/** Retrieve value for key, marks as recently used */
get(key: K): V | undefined;
/** Retrieve value without marking as recently used */
peek(key: K): V | undefined;
/** Check if key exists in cache */
has(key: K): boolean;
/** Remove specific key from cache */
delete(key: K): boolean;
/** Set key-value pair and return evicted item if any */
setpop(key: K, value: V): V | undefined;
/** Remove all items from cache */
clear(): void;
/** Iterate over values in LRU order (oldest first) */
values(): IterableIterator<V>;
/** Iterate over keys in LRU order (oldest first) */
keys(): IterableIterator<K>;
/** Iterate over [key, value] pairs in LRU order */
entries(): IterableIterator<[K, V]>;
/** Default iterator (same as entries) */
[Symbol.iterator](): IterableIterator<[K, V]>;
/** Execute callback for each item in LRU order */
forEach(callback: (value: V, key: K, cache: this) => void): void;
/** Debug representation */
inspect(): any;
}Usage Examples:
import {LRUCache} from "mnemonist";
// Basic string cache
const cache = new LRUCache<string, any>(100);
cache.set("user:123", {name: "Alice", age: 30});
cache.set("user:456", {name: "Bob", age: 25});
const user = cache.get("user:123"); // Marks as recently used
console.log(user?.name); // "Alice"
// Check without affecting LRU order
const peeked = cache.peek("user:456");
// With typed arrays for performance
const typedCache = new LRUCache(Array, Array, 1000);
// Set and get evicted item
const evicted = cache.setpop("new_key", "new_value");
if (evicted) {
console.log("Evicted:", evicted);
}
// Iteration in LRU order (oldest first)
for (const [key, value] of cache) {
console.log(`${key}: ${value}`);
}LRU Cache optimized for frequent deletions with explicit delete functionality.
/**
* LRU Cache optimized for frequent deletions
* @param capacity Maximum number of items to store
*/
function LRUCacheWithDelete<K, V>(capacity: number): LRUCacheWithDelete<K, V>;
interface LRUCacheWithDelete<K, V> {
/** Maximum number of items the cache can hold */
readonly capacity: number;
/** Current number of items in the cache */
readonly size: number;
/** Store key-value pair, evicts oldest if at capacity */
set(key: K, value: V): this;
/** Retrieve value for key, marks as recently used */
get(key: K): V | undefined;
/** Retrieve value without marking as recently used */
peek(key: K): V | undefined;
/** Check if key exists in cache */
has(key: K): boolean;
/** Remove specific key from cache (optimized operation) */
delete(key: K): boolean;
/** Remove all items from cache */
clear(): void;
/** Iterate over values in LRU order */
values(): IterableIterator<V>;
/** Iterate over keys in LRU order */
keys(): IterableIterator<K>;
/** Iterate over [key, value] pairs in LRU order */
entries(): IterableIterator<[K, V]>;
/** Default iterator (same as entries) */
[Symbol.iterator](): IterableIterator<[K, V]>;
/** Execute callback for each item in LRU order */
forEach(callback: (value: V, key: K, cache: this) => void): void;
/** Debug representation */
inspect(): any;
}Usage Examples:
import {LRUCacheWithDelete} from "mnemonist";
// Cache optimized for frequent deletions
const cache = new LRUCacheWithDelete<string, any>(50);
// Standard operations
cache.set("temp:1", {data: "temporary"});
cache.set("temp:2", {data: "also temporary"});
// Efficient deletion (the key difference)
cache.delete("temp:1"); // Optimized for this use case
// Use when you frequently remove items before they're evicted
const sessionCache = new LRUCacheWithDelete<string, SessionData>(1000);
sessionCache.set("session123", sessionData);
// Later, when session expires:
sessionCache.delete("session123"); // Efficient removalMap-like LRU cache implementing the standard Map interface.
/**
* Map-like LRU cache with standard Map interface
* @param capacity Maximum number of items to store
*/
function LRUMap<K, V>(capacity: number): LRUMap<K, V>;
interface LRUMap<K, V> extends Map<K, V> {
/** Maximum number of items the map can hold */
readonly capacity: number;
/** Current number of items in the map */
readonly size: number;
/** Store key-value pair (Map interface) */
set(key: K, value: V): this;
/** Retrieve value for key (Map interface) */
get(key: K): V | undefined;
/** Check if key exists (Map interface) */
has(key: K): boolean;
/** Remove specific key (Map interface) */
delete(key: K): boolean;
/** Remove all items (Map interface) */
clear(): void;
/** Retrieve value without marking as recently used */
peek(key: K): V | undefined;
/** Standard Map iteration methods */
values(): IterableIterator<V>;
keys(): IterableIterator<K>;
entries(): IterableIterator<[K, V]>;
[Symbol.iterator](): IterableIterator<[K, V]>;
forEach(callback: (value: V, key: K, map: this) => void): void;
/** Debug representation */
inspect(): any;
}Usage Examples:
import {LRUMap} from "mnemonist";
// Drop-in replacement for Map with LRU eviction
const lruMap = new LRUMap<string, number>(100);
// Standard Map operations
lruMap.set("a", 1);
lruMap.set("b", 2);
console.log(lruMap.get("a")); // 1
console.log(lruMap.has("b")); // true
console.log(lruMap.size); // 2
// LRU-specific operation
const peeked = lruMap.peek("a"); // Doesn't affect LRU order
// Compatible with Map-expecting code
function processMap(map: Map<string, number>) {
for (const [key, value] of map) {
console.log(`${key}: ${value}`);
}
}
processMap(lruMap); // Works seamlesslyMap-like LRU cache optimized for frequent deletions.
/**
* Map-like LRU cache optimized for frequent deletions
* @param capacity Maximum number of items to store
*/
function LRUMapWithDelete<K, V>(capacity: number): LRUMapWithDelete<K, V>;
interface LRUMapWithDelete<K, V> extends Map<K, V> {
/** Maximum number of items the map can hold */
readonly capacity: number;
/** Current number of items in the map */
readonly size: number;
/** Standard Map interface with LRU eviction */
set(key: K, value: V): this;
get(key: K): V | undefined;
has(key: K): boolean;
delete(key: K): boolean; // Optimized operation
clear(): void;
/** Retrieve value without marking as recently used */
peek(key: K): V | undefined;
/** Standard Map iteration methods */
values(): IterableIterator<V>;
keys(): IterableIterator<K>;
entries(): IterableIterator<[K, V]>;
[Symbol.iterator](): IterableIterator<[K, V]>;
forEach(callback: (value: V, key: K, map: this) => void): void;
/** Debug representation */
inspect(): any;
}Usage Examples:
import {LRUMapWithDelete} from "mnemonist";
// For scenarios with frequent deletions
const cache = new LRUMapWithDelete<string, CacheItem>(200);
// Standard Map operations
cache.set("item1", {data: "value1", expires: Date.now() + 60000});
cache.set("item2", {data: "value2", expires: Date.now() + 120000});
// Efficient deletion when items expire
setInterval(() => {
const now = Date.now();
for (const [key, item] of cache) {
if (item.expires < now) {
cache.delete(key); // Optimized for this pattern
}
}
}, 1000);/**
* Array constructor types supported by LRUCache for typed storage
*/
type ArrayConstructor =
| ArrayConstructor
| Int8ArrayConstructor
| Uint8ArrayConstructor
| Int16ArrayConstructor
| Uint16ArrayConstructor
| Int32ArrayConstructor
| Uint32ArrayConstructor
| Float32ArrayConstructor
| Float64ArrayConstructor;| Operation | LRUCache | LRUCacheWithDelete | LRUMap | LRUMapWithDelete |
|---|---|---|---|---|
| Get | O(1) | O(1) | O(1) | O(1) |
| Set | O(1) | O(1) | O(1) | O(1) |
| Delete | O(1) | O(1) optimized | O(1) | O(1) optimized |
| Peek | O(1) | O(1) | O(1) | O(1) |
| Has | O(1) | O(1) | O(1) | O(1) |
| Space | O(n) | O(n) | O(n) | O(n) |
Where n is the cache capacity.
const responseCache = new LRUCache<string, Response>(1000);
async function cachedFetch(url: string): Promise<Response> {
const cached = responseCache.get(url);
if (cached) return cached;
const response = await fetch(url);
responseCache.set(url, response);
return response;
}const sessions = new LRUCacheWithDelete<string, SessionData>(10000);
// Add session
sessions.set(sessionId, sessionData);
// Remove on logout (frequent operation)
sessions.delete(sessionId);const memoCache = new LRUMap<string, number>(500);
function expensiveComputation(input: string): number {
if (memoCache.has(input)) {
return memoCache.get(input)!;
}
const result = /* expensive calculation */;
memoCache.set(input, result);
return result;
}