Cache class

A simple in-memory cache with generic support and multiple access patterns.

Example

const cache = new Cache<string, number>();
cache.set("answer", 42);
console.log(cache.get("answer")); // 42

Constructors

constructor constructor

Signature

<K extends string | number, V>(): Cache<K, V>

Type Parameters

K

The type of cache keys

V

The type of cached values

Methods

cleanup method

Signature

(): number

Clear all expired entries from the cache.

Returns

Number of entries removed

clear method

deprecated

Use cleanup instead Clear the entire cache.

Signature

(): void

get (1/2) method

Signature

(key: K): V

Example

const value = cache.get("myKey");

Parameters

key

The cache key

Returns

The cached value, or undefined if not found or expired

get (2/2) method

Signature

<F extends () => V>(key: K, factory: F): V

Example

const value = cache.get("myKey", () => expensiveComputation());

Parameters

key

The cache key

factory

Function to generate value if not cached

Returns

The cached value, or generated value from factory

set method

Signature

(key: K, value: V, ttl?: number): void

Set a value in the cache.

Parameters

key

The cache key

value

The value to cache

ttl

Optional time-to-live in milliseconds