Created
October 9, 2015 09:08
-
-
Save jpommerening/18cf7b009fbf1e273c4a to your computer and use it in GitHub Desktop.
a minimal lru structure for js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Create dead-simple LRU structure. | |
* @param {Number} size maximum number of items to be stored. | |
* @param {Object} [init] initial contents. | |
* @return {Object} the LRU object | |
*/ | |
function LRU( size, init ) { | |
var items = init || Object.create( null ); | |
var keys = Object.keys( items ); | |
function pop( key ) { | |
var value = items[ key ]; | |
var index = keys.indexOf( key ); | |
delete items[ key ]; | |
if( index >= 0 ) { | |
keys.splice( index, 1 ); | |
} | |
return value; | |
} | |
function push( key, value ) { | |
keys.push( key ); | |
items[ key ] = value; | |
if( keys.length > size ) { | |
delete items[ keys.shift() ]; | |
} | |
} | |
function use( key ) { | |
var index = keys.indexOf( key ); | |
if( index >= 0 ) { | |
keys.splice( index, 1 ); | |
keys.push( index ); | |
} | |
} | |
return { | |
has: function has( key ) { | |
return key in items; | |
}, | |
get: function get( key ) { | |
use( key ); | |
return items[ key ]; | |
}, | |
set: function set( key, value ) { | |
pop( key ); | |
push( key, value ); | |
return value; | |
}, | |
push: push, | |
pop: pop, | |
clear: function clear() { | |
items = {}; | |
keys = []; | |
} | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment