Created
May 25, 2010 22:56
-
-
Save creationix/413798 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/*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