cache-types
v1.0.6
Published
Easily use LRU, MRU, FIFO, LIFO and RR cache interfaces, or create your own policy-based cache interface. Powererd by on-demand-loading, free of timers and never polluting the event loop.
Downloads
6
Readme
Cache Types Documentation
This package provides interfaces for creating various types of cache objects with different eviction policies. It includes pre-configured options such as FIFO (First-In, First-Out), LIFO (Last-In, First-Out), RR (Random Eviction), MRU (Most Recently Used), and LRU (Least Recently Used) cache interfaces, along with a customizable option that allows you to define other eviction policies.
Installation
npm install cache-typesUsage
Here's an example of how to use the package to create a custom cache type with a specific eviction policy:
const { CacheConstructor } = require('cache-types');
// Create a custom cache type that evicts the first two keys added
const DoubleEvictionCache = CacheConstructor(
(storageMap, self) => {
self.del(self.firstKey); // Remove the first key
self.del(self.firstKey); // Remove the second key
},
{ relocationOnGet: true } // When keys are attained with 'get', relocate them as the last ones to evict
);
// Create a new custom cache instance
const cache = new DoubleEvictionCache(100, { ttl: 1000 });
cache.set(9, 1000);
console.log(cache.get(9)); // Outputs: 1000API Documentation
CacheConstructor(_evictionPolicy = () => {}, { relocationOnGet = false })
Creates a new custom cache type based on the provided eviction policy and relocation settings.
Parameters:
- _evictionPolicy: A function that defines the eviction logic. It receives two parameters:
storageMap: The internal storage map of the cache as aMap.self: Represents the keywordthisinside the class.
- relocationOnGet: A boolean value that determines whether to relocate keys upon retrieval (
true) or not (false). This is useful for time-aware policies but may not be ideal for position-aware policies like FIFO.
Returns:
A new ES6 class extending NoPolicyCache, with the new name.
Example Usage of CacheConstructor
const CustomCache = CacheConstructor(
(storageMap, self) => {
// Eviction logic here
const keys = [...storageMap.keys()];
if (keys.length > 0) {
self.del(keys[0]); // Remove the first key
}
if (keys.length > 1) {
self.del(keys[1]); // Remove the second key
}
},
{ relocationOnGet: true }
);Cache Class (Cache)
The Cache class is a base class that provides the core functionality for cache storage and eviction. It includes methods to set, get, delete keys, and more.
Pre-configured cache types:
LRUCache: A least recently used (LRU) cache that evicts items based on their last access time.MRUCache: A most recently used (MFU) cache that evicts items based on their frequency of access.FIFOCache: A first-in, first-out (FIFO) cache that evicts items based on their order of insertion.LIFOCache: A last-in, first-out (LIFO) cache that evicts items based on their order of insertion.RandomCache: A random cache that evicts a random item
Shared Methods for the Cache class and all pre-configured cache types:
constructor(capacity, ttl, { relocationOnGet = true }): Initializes the cache with a given capacity and optional time-to-live (TTL).- Parameters:
capacity: The maximum number of items the cache can hold.ttl: The time-to-live for cached items in milliseconds.relocationOnGet: Determines whether to relocate keys upon retrieval (true) or not (false).
- Parameters:
get size: Returns the current number of items in the cache.get capacity: Returns the maximum capacity of the cache.get keys: Returns an array of all keys currently in the cache.get values: Returns an array of all values currently in the cache.get first: Returns the value of the oldest item in the cache.get last: Returns the value of the most recently added item in the cache.get firstKey: Returns the key of the oldest item in the cache.get lastKey: Returns the key of the most recently added item in the cache.get lastHit: Returns the key of the most recently accessed item.get stats: Returns the statistics object tracking hits, misses, expired items, and evicted items.evictionPolicy(storageInstance): Defines the eviction logic for the cache. This method should be overridden by subclasses to implement specific eviction policies.evict(): Evicts an item based on the configured eviction policy.flushStats(): Resets the statistics object.flush(): Clears all items from the cache.has(key): Checks if a key exists in the cache.peek(key): Returns the value of a key without updating hit stats.del(key): Removes and returns the value of a key.get(key): Retrieves a key's value, updates hit stats, and relocates keys if relocationOnGet is set to true.set(key, value, ttl): Adds or updates a key with an optional TTL.getInfo(key): Returns information about the cached item including its timestamp and remaining TTL.resize(size): Changes the cache capacity and evicts extra items if necessary.
Usage Examples: (MRUCache | RRCache | FIFOCache | LIFOCache | LRUCache)
The Most Recently Used (MRU) cache removes the most recently used item first. When a new item is added and the cache is full, the most recently used item is removed.
Class Usage:
const { MRUCache } = require('cache-types');
// Create an instance of MRUCache with a capacity of 3
const mruCache = new MRUCache(3);
mruCache.set('key1', 'value1');
mruCache.set('key2', 'value2');
mruCache.set('key3', 'value3');
console.log(mruCache.get('key3')); // Outputs: value3
// Adding a new item will evict the most recently used one (key3)
mruCache.set('key4', 'value4');
console.log(mruCache.get('key3')); // Outputs: undefined, the value was evicted