Minimal implementation of a cache using javascript's Map. Lightweight and easy to use. Includes typescript typings.
Just install the package
$ npm install @yakiyo/cache-js
# or
$ yarn add @yakiyo/cache-js
# or
$ pnpm add @yakiyo/cache-js
Import the package in your file and initialize the class
// Es6 imports
import Cache from '@yakiyo/cache-js';
// Commonjs require
const Cache = require('@yakiyo/cache-js');
const cache = new Cache<k, v>(60);
The constructor takes a number which indicated the default duration in seconds upto which the cache should remain valid. You can also set duration per entry with the add method. The default is 0 if not specified while initiating.
The Cache class extends javascript's base Map class, so every method of Map can be used on instances of the cache class too.
Checks if a key is valid or not based on its duration.
cache.valid('key-name'); // true or false
Adds a new entry to the cache. Duration is the time in seconds till which the entry should be valid. If unspecified, it uses the default duration specified while initiating the class. If even that is set to 0, the entry remains forever valid.
cache.add('key', 'value', 20); // this
Adds multiple entries to the cache. The duration is the default duration set during initialization. It takes multiple arguments, each of them being an array. The array being composed to two elements, the first one being the key, the second one being the value
cache.addMany(['k1', 'v1'], ['k2', 'v2'], ['k3', 'v3']) // this
Fetches a value from the cache. Returns undefined if the key doesn't exist or if the key expires. If the key expires, it is internally deleted.
cache.fetch('key'); // 'value'
cache.fetch('non-existent-key'); // undefined
cache.fetch('expired-key'); // undefined
Removes an entry from the cache
cache.remove('key'); // this
Removes multiple entries from the cache. It takes multiple arguments, each of them being a key, the key of the entry to remove
cache.removeMany('key 1', 'key 2', 'key 3') // this
Clears all expired entries from the cache.
cache.sweep(); // cache
Returns an array of all the values of cache
cache.toArray(); // ['value 1', 'value 2']
Returns a new map of the key value pairs in the cache
cache.toMap() // [Map Object]
This project is inspired by @discordjs/Collection
Cache-js © Yakiyo. Authored and maintained by Yakiyo.
Released under MIT License