🗃️ A cache whose entries expire a fixed time after they are written.

Info

No timers are used, deliberately — a timer per entry would hold the event loop open and keep a process alive past its work. Expiry is lazy: an entry is dropped when it is next looked at, and size and the iteration methods sweep before reporting.

Syntax

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

new TtlCache<K, V>(ttl: number);

Parameters

NameTypeDescription
ttlnumberHow long an entry stays valid, in milliseconds.

Throws a RangeError unless ttl is a positive finite number.

Members

MemberReturnsDescription
get(key)V | undefinedReads a value, or undefined if expired.
set(key, value, ttl?)thisWrites a value, optionally with its own lifetime.
has(key)booleanChecks for an unexpired key.
ttlOf(key)number | undefinedMilliseconds left before the key expires.
delete(key)booleanRemoves a key.
clear()voidRemoves every entry.
prune()numberDrops expired entries now; returns how many.
sizenumberUnexpired entries, after sweeping.
defaultTtlnumberThe configured lifetime.
keys() / values() / entries()iteratorUnexpired entries, in insertion order.

Examples

TypeScript
const cache = new TtlCache<string, number>(1000);

cache.set('a', 1);
cache.get('a'); //=> 1

// ...over a second later
cache.get('a'); //=> undefined

A per-entry lifetime overrides the default, and rewriting a key restarts it:

TypeScript
cache.set('short', 1, 50);   // expires in 50ms
cache.set('a', 2);           // 'a' gets a fresh second
Warning

A cache that is written to but never read holds expired entries until something touches it. Call prune() if that matters.

TypeScript
cache.prune(); //=> 2  (the number removed)
Last updated on
Edit this page