Toad Cache: LRU and FIFO Caching

3.7.0 · active · verified Sun Apr 19

Toad Cache is a JavaScript/TypeScript library offering in-memory Least-Recently-Used (LRU) and First-In-First-Out (FIFO) caching strategies suitable for both client-side (browser) and server-side (Node.js) environments. The current stable version is 3.7.0. Releases appear to be ad-hoc, driven by feature additions and bug fixes rather than a strict schedule. A key differentiator since version 3.0.0 is the direct export of `Lru` and `Fifo` classes, allowing direct instantiation with `new` rather than a factory function, providing a more idiomatic class-based API. It also supports optional cache statistics tracking (hit/miss/expiration) via the `LruHitStatistics` class and offers both Map-based and Object-based internal implementations for performance tuning. It provides methods for setting, getting, deleting, and managing cache entries, along with properties for cache size and configuration.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates the instantiation and basic usage of LRU and FIFO caches, including setting, getting, deleting, and integrating with the optional hit/miss/expiration statistics tracking.

import { Lru, Fifo, LruHitStatistics, HitStatisticsRecord } from 'toad-cache';

// Basic LRU Cache
const lruCache = new Lru(100, 5000); // Max 100 items, 5 seconds TTL
lruCache.set('key1', 'value1');
console.log('LRU get key1:', lruCache.get('key1'));
lruCache.set('key2', { data: 'value2' });
console.log('LRU size:', lruCache.size);
lruCache.delete('key1');
console.log('LRU keys after delete:', lruCache.keys());

// Basic FIFO Cache
const fifoCache = new Fifo(50); // Max 50 items
fifoCache.set('fkey1', 'fvalue1');
fifoCache.set('fkey2', 'fvalue2');
console.log('FIFO get fkey1:', fifoCache.get('fkey1'));

// LRU Cache with Hit Statistics
const sharedRecord = new HitStatisticsRecord();
const statsCache = new LruHitStatistics({
  cacheId: 'my-app-cache',
  globalStatisticsRecord: sharedRecord,
  statisticTtlInHours: 1, // Reset stats hourly
  max: 10,
  ttlInMsecs: 10000 // 10 seconds TTL
});

statsCache.set('skey1', 'svalue1');
statsCache.get('skey1'); // Hit
statsCache.get('skey2'); // Miss
console.log('Cache statistics:', sharedRecord.getStatistics()['my-app-cache']);

view raw JSON →