src/lru.js

Method lru

LRU factory

Parameters:

  • max must be a Number.
    ([Optional] Max size of cache, default is 1000)

Returns an Object
(LRU instance)

var lru = function ( max ) { return new LRU( max ); };

Constructor

Least Recently Used cache

Parameters:

  • max must be a Number.
    ([Optional] Max size of cache, default is 1000)
function LRU ( max ) { this.cache = {}; this.max = max || 1000; this.first = null; this.last = null; this.length = 0; }

Setting constructor loop

LRU.prototype.constructor = LRU;

Method evict

Evicts the least recently used item from cache

Returns an Object
(LRU instance)

LRU.prototype.evict = function () { if ( this.last !== null ) { this.remove( this.last ); } return this; };

Method get

Gets cached item and moves it to the front

Parameters:

  • key must be a String.
    (Item key)

Returns a Mixed
(Undefined or Item value)

LRU.prototype.get = function ( key ) { var item = this.cache[key]; if ( item === undefined ) { return; } this.set( key, item.value ); return item.value; };

Method remove

Removes item from cache

Parameters:

  • key must be a String.
    (Item key)

Returns an Object
(LRUItem instance)

LRU.prototype.remove = function ( key ) { var item = this.cache[ key ]; if ( item !== undefined ) { delete this.cache[key]; this.length--; if ( item.previous !== null ) { this.cache[item.previous].next = item.next; } if ( item.next !== null ) { this.cache[item.next].previous = item.previous; } if ( this.first === key ) { this.first = item.previous; } if ( this.last === key ) { this.last = item.next; } } return item; };

Method set

Sets item in cache as first

Parameters:

  • key must be a String.
    (Item key)

  • value can be of any type.
    (Item value)

Returns an Object
(LRU instance)

LRU.prototype.set = function ( key, value ) { var item = this.remove( key ); if ( item === undefined ) { item = new LRUItem( value ); } else { item.value = value; } item.next = null; item.previous = this.first; this.cache[key] = item; if ( this.first !== null ) { this.cache[this.first].next = key; } this.first = key; if ( this.last === null ) { this.last = key; } if ( ++this.length > this.max ) { this.evict(); } return this; };

Constructor

LRU Item factory

Parameters:

  • value can be of any type.
    (Item value)
function LRUItem ( value ) { this.next = null; this.previous = null; this.value = value; }

Setting prototype & constructor loop

LRUItem.prototype.constructor = LRUItem;