Created
June 24, 2014 09:57
-
-
Save timruffles/f4d05d2d4a47494105b6 to your computer and use it in GitHub Desktop.
parallel doing - for tests
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 doParallelNTimes(n,concurrent,fn,cb) { | |
var outstanding = 0; | |
var complete = 0; | |
var nth = 0; | |
times(Math.min(concurrent,n),loop); | |
function loop() { | |
if(outstanding >= concurrent) { | |
return; | |
} | |
outstanding += 1; | |
fn(nth,function(err,nth) { | |
outstanding -= 1; | |
complete += 1; | |
if(err) { | |
return cb(err); | |
} | |
if(complete === n) { | |
cb(); | |
} else { | |
var totalLeft = n - (complete + outstanding); | |
var unusedConcurrency = concurrent - outstanding; | |
var toLoop = Math.max(0,totalLeft < unusedConcurrency ? totalLeft : unusedConcurrency); | |
times(toLoop,loop); | |
} | |
}); | |
nth += 1; | |
} | |
} | |
function times(n,fn) { | |
while(n--) fn(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment