Best, faster, ligther, all-in-one, fully-typed cache library for JS, based on cachetools from python, with events, pooling and decorators.
All of most used cache types are included here, if what you are looking for does not exist here, tell us.
npm install cachetools-js
yarn add cachetools-js
//example cache
import { TTLCache } from 'cachetools-js'
const cache = new TTLCache({ttl: 1000})
cache['foo'] = 'bar' //recommended method
cache.set('foo', 'bar', {ttl: 500}) //second method, use this method if you wanna pass custom options
let key = cache['foo'] //recommended method
let key = cache.get('foo') //second method
cache.del('foo')
let key = cache.take('foo')
cache['foo'] //will be undefined
cache.delAll()
let keys = cache.keys()
let values = cache.values()
let length = cache.length()
cache.on('get', key => console.log(key))
cache.on('set', ({key, value}) => console.log(key, value))
cache.on('del', key => console.log(key))
Trigged when key expires, by a TTL, LRU, LFU...
cache.on('expired', key => console.log(key))
You can store all your caches in one variable, recommended in big projects to organize code
import { CachePool } from 'cachetools-js'
const pool = new CachePool({maxsize: 10})
//create a new TTLCache in pool, this function return the new cache
pool.createCache('c1', 'ttl', {ttl: 10})
const cache = pool.getCache('c1')
pool.delCache('c1')
pool.delAllCaches()
pool.createCache('c1', 'ttl', {ttl: 10})
pool.set('c1', 'key', 'value')
pool.createCache('c1', 'ttl', {ttl: 10})
const cache = pool.get('c1', 'key')
pool.createCache('c1', 'ttl', {ttl: 10})
pool.del('c1', 'key')
pool.createCache('c1', 'ttl', {ttl: 10})
pool.delAll('c1')
pool.createCache('c1', 'ttl', {ttl: 10})
const length = pool.length()
You can decore a function to apply caching if you use same args
import { cacheDecorator, TTLCache } from 'cachetools-js'
//function to sum values
const fn = (...args: number[]) => args.reduce((p, c) => p + c)
const cache = new TTLCache({ttl: 1000})
const decoredFn = cacheDecorator(fn, cache)
//will store result in cache and return
await decoredFn(1, 2, 3)
//will return cached value -- second call
await decoredFn(1, 2, 3)
//if you change args, the process will repeat