Skip to content

Instantly share code, notes, and snippets.

@nemtsov
Created October 21, 2013 20:01
Show Gist options
  • Save nemtsov/7089970 to your computer and use it in GitHub Desktop.
Save nemtsov/7089970 to your computer and use it in GitHub Desktop.
async.map that works with sparse arrays
function asyncMap(sparseArr, factory, cb) {
var completed = []
, sparseLen = sparseArr.length
, len = 0
, ctr = 0
, isDone = false
, item
, i;
function done(err, good) {
if (isDone) return;
if (err) {
isDone = true;
return cb(err);
}
completed.push(good);
item = sparseArr[i];
if (++ctr === len) cb(null, completed);
}
function doOne(item) {
process.nextTick(function () {
factory(item, done);
});
}
for (i = 0; i < sparseLen; i++) {
item = sparseArr[i];
if ('undefined' === typeof item) continue;
len++;
doOne(item);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment