Skip to content

Instantly share code, notes, and snippets.

@cloudhead
Forked from creationix/safe.js
Created May 31, 2010 07:04
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 cloudhead/419614 to your computer and use it in GitHub Desktop.
Save cloudhead/419614 to your computer and use it in GitHub Desktop.
/*jslint white: true, onevar: true, undef: true, nomen: true, eqeqeq: true,
plusplus: true, bitwise: true, regexp: true, immed: true, maxlen: 78,
indent: 2 */
// Does short term (100ms) in-memory caching and combines concurrent requests
// to the same resource into a single callback group.
var Safe = module.exports = function Safe(fn, expires) {
// return fn;
var cache = {},
queues = {};
return function (key, callback) {
if (key in cache) {
return callback(null, cache[key]);
}
if (!(key in queues)) {
queues[key] = [];
}
var queue = queues[key];
if (queue.length > 0) {
queue.push(callback);
return;
}
queue[0] = callback;
fn(key, function (err, data) {
var results;
for (var i = 0, l = queue.length; i < l; i += 1) {
queue[i](err, data);
}
queue.length = 0;
if (!err) {
cache[key] = data;
setTimeout(function () {
delete cache[key];
}, expires || 100);
}
});
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment