Skip to content

Instantly share code, notes, and snippets.

@rickcrawford
Last active August 29, 2015 13:56
Show Gist options
  • Save rickcrawford/8971662 to your computer and use it in GitHub Desktop.
Save rickcrawford/8971662 to your computer and use it in GitHub Desktop.
Sizable Hash with expiring keys for storing objects in memory in Node.js. Oldest object will be removed from the hash once the limit is reached.
//created by Rick Crawford - https://github.com/rickcrawford
var _ = require("underscore"),
bunyan = require('bunyan');
var log = bunyan.createLogger({
name: "test",
stream: process.stdout,
level: 'debug'
});
function L1(max) {
this.values = {};
this.keys = [];
this.maxSize = max || 100;
};
L1.prototype.set = function(key, value, ttl) {
log.debug('setL1', key, value, ttl);
//remove the key if it exists...
this.delete(key);
//set the values
this.values[key] = value;
this.keys.push(key);
//only resize if necessary
if (this.keys.length > this.maxSize) {
log.debug('current keys:', this.keys);
//remove oldest key...
var k = this.keys.shift();
this.delete(k);
log.debug('deleted key: %s from L1', k);
}
if (ttl && ttl > 0) {
log.debug('setting timeout %d for key %s', ttl, key);
var that = this;
setTimeout(function() {
log.debug('expiring L1 key %s', key);
that.delete(key);
}, ttl);
}
};
L1.prototype.size = function() {
return this.values.length;
}
L1.prototype.delete = function(key) {
delete this.values[key];
this.keys = _.without(this.keys, key);
this.length = this.values.length;
};
L1.prototype.get = function(key) {
return this.values[key];
};
L1.prototype.keys = function() {
return this.keys;
}
L1.prototype.toString = function() {
return JSON.stringify(this.values);
};
var l1cache = new L1();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment