🗃️ A fixed-capacity cache that evicts the least recently used entry once it is full.

Info

Recency is tracked by Map insertion order — reading or writing a key moves it to the end, so the oldest key is always the first the map yields. Every operation is O(1) with no auxiliary linked list.

Syntax

TypeScript
import { LruCache } from '@opentf/std';

new LruCache<K, V>(maxSize: number);

Parameters

NameTypeDescription
maxSizenumberThe number of entries to hold before evicting.

Throws a RangeError unless maxSize is a positive integer.

Members

MemberReturnsDescription
get(key)V | undefinedReads a value and marks it most recently used.
peek(key)V | undefinedReads a value without affecting eviction order.
set(key, value)thisWrites a value, marking it most recently used.
has(key)booleanChecks a key. Does not count as a use.
delete(key)booleanRemoves a key.
clear()voidRemoves every entry.
sizenumberEntries currently held.
maxSizenumberThe configured capacity.
keys() / values() / entries()iteratorLeast recently used first.
forEach(cb)voidVisits every entry.

Examples

TypeScript
const cache = new LruCache<string, number>(2);

cache.set('a', 1);
cache.set('b', 2);
cache.get('a');    // 'a' is now the most recently used
cache.set('c', 3); // evicts 'b', not 'a'

cache.has('b'); //=> false
cache.has('a'); //=> true

peek inspects without disturbing what is about to be evicted:

TypeScript
cache.peek('a'); // does not count as a use

Iteration runs least recently used first, so the next eviction is at the front:

TypeScript
[...cache.keys()] //=> ['c', 'a']
Last updated on
Edit this page