Skip to content

Instantly share code, notes, and snippets.

@jhurliman
Created October 28, 2011 00:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jhurliman/1321299 to your computer and use it in GitHub Desktop.
Save jhurliman/1321299 to your computer and use it in GitHub Desktop.
A generic expiring cache
Cache = function(cleanupIntervalMS) {
if (typeof cleanupIntervalMS === 'undefined')
cleanupIntervalMS = 1000 * 60 * 5; // 5 minute default interval
if (cleanupIntervalMS)
this.cleanupTimer = setInterval(this.cleanup, cleanupIntervalMS);
};
Cache.prototype = {
store: {},
/**
* key - Key of the value to retrieve.
* insertCallback(fn) - Fired when the key is not found in the cache and no
* lookup is currently running for the requested key. fn expects three
* parameters: an error message (or null), the value to cache, and the
* cache lifetime in milliseconds.
* foundCallback(err, value) - Fired when the key is resolved to a value.
*/
get: function(key, insertCallback, foundCallback) {
var obj = this.store[key];
if (obj) {
if (obj.callbacks)
return obj.callbacks.push(foundCallback);
else if (obj.expiration <= +new Date())
delete this.store[key];
else
return foundCallback(null, obj.value);
}
obj = { callbacks: [foundCallback] };
this.store[key] = obj;
insertCallback(function(err, newValue, lifetimeMS) {
for (var i = 0; i < obj.callbacks.length; i++)
value.callbacks[i](err, newValue);
obj.value = newValue;
obj.expiration = new Date() + lifetimeMS;
this.store[key] = obj;
});
},
cleanup: function() {
var now = +new Date();
for (var key in this.store) {
var obj = this.store[key];
if (obj.expiration && obj.expiration <= now)
delete this.store[key];
}
},
};
module.exports = Cache;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment