typescript-lru-cache
This is a simple LRU cache implementation written in Typescript.
An LRU cache will evict the least recently used item to make room for new items.
Useful for when a cache size should be limited but the most used items should be kept.
Installation:
npm i typescript-lru-cache
Why use this LRU Cache?
This library was written in Typescript so type definitions are included out of the box and are always up to date. The Typescript source code is included in the package so users can easily look at the implementation. This cache uses a Map
object for internal entry tracking, so any type can be used as a key (including reference types!). Also, this library has no run-time dependencies!
Usage:
See TypeDoc documentation here.
import { LRUCache } from 'typescript-lru-cache';
const cache = new LRUCache<string, string>();
cache.set('testKey', 'testValue');
const value = cache.get('testKey');
console.log(value);
Options:
LRUCache Options:
Pass in an optional options object into the constructor of the LRU cache.
The options object has the following properties:
export interface LRUCacheOptions<TKey, TValue> {
maxSize?: number;
entryExpirationTimeInMS?: number | null;
onEntryEvicted?: (evictedEntry: { key: TKey; value: TValue; isExpired: boolean }) => void;
onEntryMarkedAsMostRecentlyUsed?: (entry: { key: TKey; value: TValue }) => void;
clone?: boolean;
cloneFn?: (value: TValue) => TValue;
}
Example using options:
import { LRUCache } from 'typescript-lru-cache';
const cache = new LRUCache<string, string>({
maxSize: 100,
entryExpirationTimeInMS: 5000,
onEntryEvicted: ({ key, value, isExpired }) =>
console.log(`Entry with key ${key} and value ${value} was evicted from the cache. Expired: ${isExpired}`),
onEntryMarkedAsMostRecentlyUsed: ({ key, value }) =>
console.log(`Entry with key ${key} and value ${value} was just marked as most recently used.`)
});
cache.set('testKey', 'testValue');
const value = cache.get('testKey');
console.log(value);
LRUCache Set Entry Options:
Pass in an optional options object as the third argument of the set
method to configure options for just that entry. These options will override LRUCache options if applicable (including callback methods like onEntryEvicted).
The options object has the following properties:
export interface LRUCacheSetEntryOptions<TKey, TValue> {
entryExpirationTimeInMS?: number | null;
onEntryEvicted?: (evictedEntry: { key: TKey; value: TValue; isExpired: boolean }) => void;
onEntryMarkedAsMostRecentlyUsed?: (entry: { key: TKey; value: TValue }) => void;
clone?: boolean;
cloneFn?: (value: TValue) => TValue;
}
Example:
const cache = new LRUCache({ entryExpirationTimeInMS: 1000 });
cache.set('key', 'value', { entryExpirationTimeInMS: 10000 });
API
set(key, value, options?)
Sets the value for the key in the LRUCache object. Returns the LRUCache object. This marks the newly added entry as the most recently used entry. If adding the new entry makes the cache size go above maxSize, this will evict the least recently used entries until size is equal to maxSize.
const cache = new LRUCache();
cache.set('testKey', 'testValue');
cache.set('key2', 'value2', { entryExpirationTimeInMS: 10 });
get(key)
Returns the value associated to the key, or null if there is none or if the entry is expired. If an entry is returned, this marks the returned entry as the most recently used entry.
const cache = new LRUCache();
cache.set('testKey', 'testValue');
const item1 = cache.get('testKey');
const item2 = cache.get('keyNotInCache');
peek(key)
Returns the value associated to the key, or null if there is none or if the entry is expired. If an entry is returned, this will not mark the entry as most recently accessed. Useful if a value is needed but the order of the cache should not be changed.
const cache = new LRUCache();
cache.set('testKey', 'testValue');
const item1 = cache.peek('testKey');
const item2 = cache.peek('keyNotInCache');
delete(key)
Deletes the entry for the passed in key. Returns true if item was deleted. False if item is not in cache.
const cache = new LRUCache();
cache.set('testKey', 'testValue');
const wasDeleted = cache.delete('testKey');
const wasDeleted2 = cache.delete('keyNotInCache');
has(key)
Returns a boolean asserting whether a value has been associated to the key in the LRUCache object or not. This does not mark the entry as recently used.
const cache = new LRUCache();
cache.set('testKey', 'testValue');
const wasDeleted = cache.has('testKey');
const wasDeleted2 = cache.has('keyNotInCache');
clear()
Removes all entries in the cache.
const cache = new LRUCache();
cache.set('testKey', 'testValue');
cache.clear();
find(entry => boolean)
Searches the cache for an entry matching the passed in condition. If multiply entries in the cache match the condition, the most recently used entry will be returned. If an entry is returned, this marks the returned entry as the most recently used entry. Expired entries will be skipped (and removed).
const cache = new LRUCache();
cache.set('testKey', 'testValue');
const item = cache.find(entry => {
const { key, value } = entry;
if (key === 'testKey' || value === 'something') {
return true;
}
return false;
});
const item2 = cache.find(entry => entry.key === 'notInCache');
forEach((key, value, index) => void)
Iterates over and applies the callback function to each entry in the cache. Iterates in order from most recently accessed entry to least recently. Expired entries will be skipped (and removed). No entry will be marked as recently used.
const cache = new LRUCache();
cache.set('testKey', 'testValue');
cache.forEach((key, value, index) => {
});
values()
Creates a Generator which can be used with for ... of ... to iterate over the cache values. Iterates in order from most recently accessed entry to least recently. Expired entries will be skipped (and removed). No entry will be marked as accessed.
const cache = new LRUCache();
cache.set('testKey', 'testValue');
for (const value of cache.values()) {
}
keys()
Creates a Generator which can be used with for ... of ... to iterate over the cache keys. Iterates in order from most recently accessed entry to least recently. Expired entries will be skipped (and removed). No entry will be marked as accessed.
const cache = new LRUCache();
cache.set('testKey', 'testValue');
for (const key of cache.keys()) {
}
entries()
Creates a Generator which can be used with for ... of ... to iterate over the cache entries. Iterates in order from most recently accessed entry to least recently. Expired entries will be skipped (and removed). No entry will be marked as accessed.
const cache = new LRUCache();
cache.set('testKey', 'testValue');
for (const entry of cache.entries()) {
const { key, value } = entry;
}
[Symbol.iterator]()
Creates a Generator which can be used with for ... of ... to iterate over the cache entries. Iterates in order from most recently accessed entry to least recently. Expired entries will be skipped (and removed). No entry will be marked as accessed.
const cache = new LRUCache();
cache.set('testKey', 'testValue');
for (const entry of cache) {
const { key, value } = entry;
}
size
Returns the number of entries in the LRUCache.
const cache = new LRUCache();
cache.set('testKey', 'testValue');
const size = cache.size;
console.log(size);
remainingSize
Returns the number of entries that can still be added to the LRUCache without evicting existing entries.
const cache = new LRUCache({ maxSize: 10 });
cache.set('testKey', 'testValue');
const remainingSize = cache.remainingSize;
console.log(remainingSize);
newest
Returns the most recently used (newest) entry in the cache. This will not mark the entry as recently used.
const cache = new LRUCache({ maxSize: 10 });
cache.set('testKey', 'testValue');
const newest = cache.newest;
console.log(newest.value);
console.log(newest.key);
oldest
Returns the least recently used (oldest) entry in the cache. This will not mark the entry as recently used.
const cache = new LRUCache({ maxSize: 10 });
cache.set('testKey', 'testValue');
const oldest = cache.oldest;
console.log(oldest.value);
console.log(oldest.key);
maxSize
Gets or sets the maxSize of the cache. Setting this to a lower maxSize will evict the least recently used entries if needed to reach new maxSize.
const cache = new LRUCache({ maxSize: 10 });
cache.set('testKey', 'testValue');
const maxSize = cache.maxSize;
cache.maxSize = 5;