Bounded LRU (least-recently-used) map with a hard capacity.
Behaves like Map for get/set/has/delete/size/iteration, with these differences:
- Inserting a new key when size === capacity evicts the least-recently-used entry.
- get(key) marks the entry as most-recently-used.
- set(key, value) marks the entry as most-recently-used (including when overwriting).
- has(key) does NOT mark as used (matches Map parity).
- peek(key) reads without marking as used.
Iteration order is LRU → MRU, matching Map's insertion-order guarantee where "insertion"
is redefined as "last use".
Implementation uses a single backing Map and relies on its insertion-order iteration —
on use, the entry is deleted and re-inserted to move it to the MRU end.
Iterators (keys(), values(), entries(), [Symbol.iterator]) are live views over the
backing Map, not snapshots. Per the ECMAScript Map iteration spec, calling get(key) or
set(existing_key, …) during iteration moves that entry to the MRU end and causes it to be
re-visited later in the same iteration. If you need a stable view while mutating, copy first
(e.g. [...lru.entries()]).
generics
K
V
examples
const cache = new LruMap<string, Buffer>(100, {
on_evict: (key, value) => value.release(),
});
cache.set('a.png', buf_a);
cache.set('b.png', buf_b);
cache.get('a.png'); // refreshes 'a.png' as most-recently-usedcapacity
type number
constructor
type new <K, V>(capacity: number, options?: LruMapOptions<K, V> | undefined): LruMap<K, V>
capacity
maximum number of entries; must be a positive integer
numberoptions?
optional on_evict hook
LruMapOptions<K, V> | undefinedError- if `capacity` is not a positive integer
get
Returns the value for key and marks it as most-recently-used.
type (key: K): V | undefined
key
KV | undefinedpeek
Returns the value for key without affecting eviction order.
type (key: K): V | undefined
key
KV | undefinedhas
Returns true if key is present. Does NOT mark as used (matches Map).
type (key: K): boolean
key
Kbooleanset
Sets value for key and marks it as most-recently-used.
Evicts the least-recently-used entry when inserting a new key at capacity.
The on_evict hook (if any) fires AFTER the new entry is inserted.
type (key: K, value: V): this
key
Kvalue
Vthisdelete
type (key: K): boolean
key
Kbooleanclear
type (): void
void[Symbol.iterator]
type (): IterableIterator<[K, V]>
IterableIterator<[K, V]>keys
type (): IterableIterator<K>
IterableIterator<K>values
type (): IterableIterator<V>
IterableIterator<V>entries
type (): IterableIterator<[K, V]>
IterableIterator<[K, V]>