All files concurrency.js

81.25% Statements 26/32
69.57% Branches 16/23
75% Functions 3/4
88.46% Lines 23/26
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49  21x 21x   21x 21x 21x   21x   16666752x 16666752x 87x 87x 87x   16666665x 16666665x 16666665x     16666665x 16666665x     16666665x 16666665x 16666665x                         21x 87x 87x         1x  
function Mapromise(collection, callback, options = {}) {
	return new Promise(function(resolve, reject) {
		const concurrency = options.concurrency || 1;
		let iterator;
		Iif (Reflect.has(collection, 'next')) iterator = collection;
		Eif (collection[Symbol.iterator]) iterator = collection[Symbol.iterator]();
		Iif (!iterator) return reject(new Error('Not iterable'));
 
		const bulk = {
			next() {
				let current = this.iterator.next();
				if (current.done) {
					if (this.running === 0 && !this.rejected) resolve(this.accumulator || this.index);
					this.done = true;
					return;
				}
				let currentIndex = this.index;
				Promise.resolve(callback(current.value, currentIndex))
					.then((result) => this.resolve(result, currentIndex))
					.catch((reason) => this.reject(reason));
 
				this.index++;
				this.running++;
			},
			resolve(result, index) {
				this.running--;
				Iif (this.accumulator) this.accumulator[index] = result;
				this.next();
			},
			reject(reason) {
				this.rejected = true;
				reject(reason);
			},
			accumulator: options.collect === false ? null : [],
			running: 0,
			index: 0,
			iterator
		};
 
 
		while(bulk.running < concurrency) {
			bulk.next();
			if (bulk.done) break;
		}
	});
}
 
module.exports = Mapromise;