What is ylru?
The ylru package is a simple and efficient LRU (Least Recently Used) cache implementation in JavaScript. It is designed to help manage a cache of items with a fixed size, automatically removing the least recently used items when the cache exceeds its capacity. This is particularly useful in applications where memory management and data retrieval efficiency are critical.
What are ylru's main functionalities?
Create and manage an LRU cache
This feature allows the user to create a cache with a specified limit and perform basic operations such as setting, getting, checking, and deleting items, as well as retrieving the size of the cache.
const YLRU = require('ylru');
let cache = new YLRU(100); // Create a cache that can hold 100 items
// Set items in the cache
cache.set('key1', 'value1');
cache.set('key2', 'value2');
// Get an item from the cache
let value = cache.get('key1'); // returns 'value1'
// Check if a key exists in the cache
let exists = cache.has('key1'); // returns true
// Remove an item from the cache
cache.delete('key2');
// Get the number of items in the cache
let size = cache.size(); // returns 1
Other packages similar to ylru
lru-cache
lru-cache is another popular LRU cache implementation. It offers additional features such as item expiration based on time, which ylru does not support. This makes lru-cache suitable for scenarios where cache items should expire after a certain duration.
node-cache
node-cache is a more general caching library that supports both LRU mechanism and other types of cache strategies. Unlike ylru, which is specifically focused on LRU, node-cache provides a more flexible solution for various caching needs.
ylru
hashlru inspired
hashlru is the Simpler, faster LRU cache algorithm.
Please checkout algorithm and complexity on hashlru.
ylru extends some features base on hashlru:
- cache value can be expired.
- cache value can be empty value, e.g.:
null
, undefined
, ''
, 0
Usage
const LRU = require('ylru');
const lru = new LRU(100);
lru.set(key, value);
lru.get(key);
lru.set(key2, value2, { maxAge: 5000 });
lru.get(key2, { maxAge: 5000 });
API
LRU(max) => lru
initialize a lru object.
lru.get(key[, options]) => value | null
{Number} options.maxAge
: update expire time when get, value will become undefined
after maxAge
pass.
Returns the value in the cache.
lru.set(key, value[, options])
{Number} options.maxAge
: value will become undefined
after maxAge
pass.
If maxAge
not set, value will be never expired.
Set the value for key.
lru.keys()
Get all unexpired cache keys from lru, due to the strategy of ylru, the keys
' length may greater than max
.
const lru = new LRU(3);
lru.set('key 1', 'value 1');
lru.set('key 2', 'value 2');
lru.set('key 3', 'value 3');
lru.set('key 4', 'value 4');
lru.keys();
License
MIT