LRU cache in JavaScript
SimpleThe implementation is inspired by node-lru-cache by Isaac Schlueter. The
motivation of this project is to provide Object.create
fallback in order to
work on IE8.
Installation
With npm
$ npm install simple-lru
With Component
$ component install smagch/simple-lru
With Bower
$ bower install simple-lru
Or download tarball.
Examples
You can set any value with a string key.
var cache = 3;cache;cache;cache;var a = cache; // a = 'A'var b = cache; // b = {name: 'smagch'}var c = cache; // c = 1000
It removes cache items automatically when total length get out of max.
var cache = 3;cache;cache;cache;cache;var a = cache; // a = undefined;var b = cache; // b = 'B'var c = cache; // c = 'C'var d = cache; // d = 'D'var keys = cache; // keys = ['b', 'c', 'd']
Since it's using LRU cache algorithm, it removes the least recently used item.
var cache = 3;cache;cache;cache;// Calling `get` with 'a', 'a' is the most recently used item.var a = cache; // a = 'A'var keys = cache; // keys = ['b', 'c', 'a'] cache;a = cache; // a = 'A'var b = cache; // b = undefinedvar c = cache; // c = 'C'var d = cache; // d = 'D'
API
new SimpleLRU(max)
Create a new SimpleLRU
instance with given max cache number. max
option
should be a positive number.
SimpleLRU#set(key, value)
Set a new cache with given key and value.
SimpleLRU#get(key)
Get a cache by key.
SimpleLRU#peek(key)
Get a cache without updating recently used order.
SimpleLRU#del(key)
Delete a cache by key.
SimpleLRU#has(key)
See if it has a cache with given key.
SimpleLRU#length()
Return total number of cache items.
SimpleLRU#reset()
Clear all stored cache.
SimpleLRU#keys()
Return an Array of existing cache keys in least recently used order. The most recently used cache item will be the last.
SimpleLRU#max([max])
Getter|Setter of max
option. Get a max
option if it has no argument. And
change max
option with an argument. It will trim cache when new max
option
is smaller than its length.
License
MIT