Repo of the Day
EvandroLG/Dadado
Published: Dec 17, 2024
Open repository ↗A cache that automatically removes the least-recently-used items
Summary
Dadado is a small TypeScript library that implements a least-recently-used (LRU) cache. It is published under the MIT license, has zero runtime dependencies, and is designed to run in both Node.js and browser environments. The package advertises a gzipped size of less than 400 bytes and exposes a minimalist class-based API.
What it is useful for
An LRU cache is useful when an application needs fast in-memory storage for a bounded set of values and is willing to discard older entries once that bound is reached. Typical situations include memoizing expensive function results, holding the most recent HTTP responses, keeping the last few search results, or storing recent UI state without growing memory unbounded. The "persistent" flag adds a small twist: specific keys can be pinned so they are skipped during automatic eviction, which is useful when a few entries must always be available (for example, a default configuration value or a logged-in user's profile) while everything else rotates in and out.
How engineers can use it
Installation is documented in the README:
npm install dadado
or
yarn add dadado
Basic usage, as shown in the README:
import Dadado from 'dadado';
// `capacity` is required and must be a positive integer
const cache = new Dadado(3);
cache.setItem('key1', 'value1');
cache.setItem('key2', 'value2');
cache.getItem('key1'); // 'value1'
cache.setItem('key3', 'value3');
// At this point, the item associated with `key2` will be evicted
// because the capacity was reached and `key1` was used before `key2`.
cache.setItem('key4', 'value4');
cache.size(); // 3
cache.contains('key2'); // false
cache.contains('key1'); // true
The constructor takes a required positive integer capacity; the README does not describe behavior when capacity is 0, negative, or non-integer, so consult the source if you need to handle those edge cases. The available methods are setItem, getItem, contains, removeItem, size, clear, and toArray, which returns key-value pairs sorted from least to most recently used. The persistent-flag helpers are setPersistent, removePersistent, and togglePersistent. Items marked persistent are not auto-evicted but can still be removed with removeItem or wiped with clear(). Because the package has no dependencies and ships TypeScript types, it can be dropped into most modern JavaScript or TypeScript projects without extra configuration.