Created
January 22, 2018 22:54
-
-
Save p0wdrdotcom/9b0bb63f426acd9a12c90d1756032938 to your computer and use it in GitHub Desktop.
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
const DEFAULT_MAX_ITEMS = 1000; | |
function LRU(size) { | |
const items = {}; | |
let max_items = DEFAULT_MAX_ITEMS; | |
if (size != null) { | |
max_items = size; | |
} | |
function contains(key) { | |
return Object.keys(items).indexOf(key) > -1; | |
} | |
function prune() { | |
if (Object.keys(items).length > max_items) { | |
setTimeout(function() { // do this on next tick to not hold up the put | |
const oldest_key = Object.keys(items).reduce(function(oldest, nextKey) { | |
if (oldest == null) { | |
return nextKey; | |
} | |
if (items[oldest].accesstime > items[nextKey].accesstime) { | |
return nextKey; | |
} | |
return oldest; | |
}, null); | |
if (oldest_key != null && contains(oldest_key)) { | |
delete items[oldest_key]; | |
} | |
prune(); // recurse to ensure we prune right back | |
}); | |
} | |
} | |
function put(key, data) { | |
if (!contains(key)) { | |
items[key] = {}; | |
} | |
items[key].data = data; | |
items[key].accesstime = Date.now(); | |
prune(); | |
} | |
function get(key) { | |
if (!contains(key)) { | |
return null; | |
} | |
items[key].accesstime = Date.now(); | |
return items[key].data; | |
} | |
function remove(key) { | |
if (!contains(key)) { | |
return; | |
} | |
delete items[key]; | |
} | |
function purge() { | |
Object.keys(items).forEach(remove); | |
} | |
return { | |
get, | |
put, | |
remove, | |
purge | |
}; | |
} | |
module.exports = LRU; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment