Created
October 21, 2013 20:01
-
-
Save nemtsov/7089970 to your computer and use it in GitHub Desktop.
async.map that works with sparse arrays
This file contains 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
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