a-simple-cache
Simple in-memory cache with additional utilities.
Cache
Cache
is a low-level interface for storing values to and retrieving values from a global object.
Importing
import { Cache } from 'a-simple-cache';
Caching a value
Cache.set('key', 'value', 60000);
Cache.set('my:id', {
'number': 42,
'string': 'Hello!',
}, 180000);
Retrieving a value
Cache.get('key');
'value'
Cache.get('my:id');
{ 'number': 42, 'string': 'Hello!' }
Checking if an entry is valid
Cache.isValid('key');
true
Cache.isValid('key');
false
Cache.isValid('my:id');
true
Cache.isValid('my:id');
false
Listing keys of entries
Cache.keys();
[ 'key', 'my:id' ]
Cache.keys(k => k.startsWith('my:'));
[ 'my:id' ]
Deleting entries
Cache.clear();
for (const key of Cache.keys()) {
if (!Cache.isValid(key)) {
Cache.delete(key);
}
}
Cache.keys();
[ ]
Utilities
time
Caching time is expressed as a number of milliseconds, but the library provides a few convenience constants.
import { time } from 'a-simple-cache';
time.second, time.minute, time.hour
1000, 60000, 3600000
time.day, time.week, time.month
86400000, 604800000, 2592000000
Memoize
Memoize
is a function wrapper that automatically caches values returned by the function for any given argument combination.
Memoizing a function with it
import { Memoize } from 'a-simple-cache';
function expensive(arg) { ... }
const memoizedExpensive = Memoize.it(expensive, time.hour);
memoizedExpensive(0);
memoizedExpensive(0);
memoizedExpensive(0);
Invalidating a function's cache with invalidate
Sometimes you need to invalidate the cache prematurely so that the function will start to run again for all argument combinations.
memoizedExpensive(1);
memoizedExpensive(1);
Memoize.invalidate(expensive);
Memoize.invalidate(memoizedExpensive);
memoizedExpensive(1);
Tests
npm test
npm run coverage