Tiny Javascript Least Recently Used cache, for both Browsers and NodeJs. No dependencies needed.
npm install --save @davidegheri/lru
# Or
yarn add @davidegheri/lru
const lru = require('@davidegheri/lru');
import lru from '@davidegheri/lru';
const maxEntries = 5; // Defaults 10
const cache = lru(maxEntries);
get(key): any
Retrieve a cached element by its key. Moves the element as head of the cache.
cache.get('key');
set(key, value): Lru
Add a new element to the cache if not already present. Moves the element as head of the cache
cache.set('key', 'fooBar');
has(key): boolean
Check if the given key exists, this not move the element as head of the cache
cache.has('key1');
delete(key): Lru
Remove a cached element by its key. Moves every other elements consequently
cache.delete('key');
reset(limit?: number): Lru
Reset the cache, deletes all cached elements, optionally change the cache limit
cache.reset();
size: number
Get the number of cached elements
cache.set('key1', 'foo');
cache.set('key2', 'bar');
console.log(cache.size) // 2
head: any
Get the head element (last used or inserted)
cache.set('key1', 'foo');
cache.set('key2', 'bar');
console.log(cache.head); // bar (key2)
console.log(cache.get('key1')); // foo
console.log(cache.head); // foo (key1)
tail: any
Get the tail element (oldest used or inserted)
cache.set('key1', 'foo');
cache.set('key2', 'bar');
console.log(cache.tail); // foo (key1)
console.log(cache.get('key1')); // foo
console.log(cache.tail); // bar (key2)