a-simple-cache
Simple in-memory cache with additional utilities, including memoization and statistics.
Basic functions
cache
is an interface for storing values to and retrieving values from a global object.
set: caching a value
import { cache } from 'a-simple-cache';
cache.set('key', 'value', 60000);
cache.set('my:id', {
'number': 42,
'string': 'Hello!',
}, 180000);
get: retrieving a value
cache.get('key');
'value'
cache.get('my:id');
{ number: 42, string: 'Hello!' }
has: checking if a key exists
cache.has('key');
true
cache.has('non-existent key');
false
isValid: checking if an entry is valid
cache.isValid('key');
true
cache.isValid('key');
false
cache.isValid('my:id');
true
cache.isValid('my:id');
false
keys: listing keys of entries
cache.keys();
[ 'key', 'my:id' ]
cache.keys(k => k.startsWith('my:'));
[ 'my:id' ]
delete: deleting entries
cache.clear();
for (const key of cache.keys()) {
if (!cache.isValid(key)) {
cache.delete(key);
}
}
cache.keys();
[ ]
time constants
Caching time is expressed as a number of milliseconds, but the library provides a few constants for convenience.
import { time } from 'a-simple-cache';
time.second, time.minute, time.hour
1000, 60000, 3600000
time.day, time.week, time.month
86400000, 604800000, 2592000000
Extended functions
memoize: memoizing a function
memoize
returns a wrapped function that automatically caches values returned by the original function for any given argument combination.
On subsequent calls to the memoized function, cached values will be retrieved instead of re-running the function.
It is possible to set a time-to-live for the cached values, after which the original function will run again and new values will be stored in the cache.
function expensive(arg) { ... }
const memoizedExpensive = cache.memoize(expensive, time.hour);
memoizedExpensive(0);
memoizedExpensive(0);
memoizedExpensive(0);
invalidate: invalidating a function's cache
Sometimes you need to invalidate a function's cache prematurely so that the function will start to run again for all argument combinations.
memoizedExpensive(0);
cache.invalidate(memoizedExpensive);
cache.invalidate(expensive);
memoizedExpensive(0);
statistics: get an overview of called cache methods
cache.enableStatistics();
cache.statistics();
{
set: 0,
delete: 0,
get: { hit: 0, miss: 0 },
isValid: { true: 0, false: 0 }
}
Tests
npm run coverage
npm run coverage:open
npm run test:mutations
npm run test:mutations:open