Skip to content

Instantly share code, notes, and snippets.

@rndme
Created February 23, 2016 08:25
Show Gist options
  • Save rndme/e602b3c974b312431a3a to your computer and use it in GitHub Desktop.
Save rndme/e602b3c974b312431a3a to your computer and use it in GitHub Desktop.
function cache(size, duration) {
// an object cache, where you can set max size or time or both, and it maintains shit for you, and quickly too
var index = {}, stack = [],
count = 0;
size = size || 100;
duration = duration || 1000 * 60 * 5;
function add(key, val) {
count++;
if(count > size) {
var old = stack.shift().key;
delete index[old];
count--;
}
index[key] = stack.length;
stack.push({
key: key,
value: val,
date: Date.now() + duration
});
return val;
}
function rem(key) {
var i = index[key];
if(i === undefined) return false;
count--;
stack.splice(i, 1);
delete index[key];
return true;
}
function get(key) {
var o = stack[index[key]] || 0;
return o.value;
}
function mon() {
var now = Date.now();
stack.every(function(entry) {
if(entry.date < now) return rem(entry.key);
});
}
setInterval(mon, duration / 2);
return {
add: add,
rem: rem,
get: get
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment