import { AsyncErrorCallback, SimpleFunction, ParallelCallback, NumericDictionary } from "../interfaces"; import { once } from "../common"; /** * This method starts functions in a series at once, but at most N functions, * should be executing in the same moment. And then executes the rest in * series in sequence. */ export function concurrent( currency: number, fns: SimpleFunction[], final?: ParallelCallback ): void { fns = fns.slice(); if (!fns.length || !currency) { return final(); } let errorNum: number = 0, completed: number = 0; let errors: NumericDictionary = {}; let c: number; let loop = function(i: number): void { fns[i](once(function(err?: E): void { completed++; if (err) { errors[i] = err; errorNum++; } if (completed === fns.length) { final(errorNum ? errors : null); } else if (c < fns.length) { loop(c++); } })); }; for (c = 0; c < currency; c++) { loop(c); } }