public
Last active — forked from creationix/safe.js

  • Download Gist
safe.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
/*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);
}
});
};
};

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.