Skip to content

Instantly share code, notes, and snippets.

@DTrejo
Created May 2, 2011 06:08
Show Gist options
  • Save DTrejo/951229 to your computer and use it in GitHub Desktop.
Save DTrejo/951229 to your computer and use it in GitHub Desktop.
expiring map, different style
// opts = { timeout: 60 }
function ExpiringMap(opts) {
var self = {}
, map = {}
, activeKeys = {
// key: clearTimeout
}
, noop = function() {};
;
self.timeout = opts.timeout * 1000 || 60 * 1000;
// k, v [, timeout, cb]
self.set = function(k, v, timeout, cb) {
if (!cb && typeof timeout === 'function') {
cb = timeout;
timeout = undefined;
}
cb = cb || noop;
timeout = timeout * 1000 || self.timeout;
map[k] = v;
activeKeys[k] = setTimeout(function() {
self.remove(k);
cb(k, v, timeout / 1000);
}, timeout);
};
self.get = function(k) {
return map[k]; // returns undefined if not contained
};
self.remove = function(k) {
clearTimeout(activeKeys[k]);
delete activeKeys[k];
delete map[k];
};
self.contains = function(k) {
return (k in activeKeys);
};
self.getKeyList = function() {
var list = [];
for (k in activeKeys) {
list.push(k);
}
return list;
};
return self;
};
var exports = exports || {};
exports.ExpiringMap = ExpiringMap;
//
// Test it
//
if (!module.parent) {
var map = new ExpiringMap({ timeout: 1 });
map.set('ohai', 'dude.', function(k, v) {
console.log('sayin', k, v);
});
console.log("map.contains('ohai') =",map.contains('ohai'));
console.log("map.get('ohai') =",map.get('ohai'));
map.set('glug', {a: 2}, 5, function(k, v, t) {
console.log(k,'=',v,'expired after non-default timeout of',t,'s');
});
map.set('deletemefast', 'please', function() {
console.log('you were not fast enough!');
});
map.remove('deletemefast');
console.log("map.contains('deletemefast') =", map.contains('deletemefast'));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment