All files series.js

84.21% Statements 16/19
66.67% Branches 10/15
100% Functions 6/6
100% Lines 12/12
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                  16x   16x   16x 16x 16x   16x         11111135x 11111135x   11111126x   11111119x 11111119x         2x  
/**
 * Kicks off the iteration
 * @method Mapromise
 * @param {Iterable} collection Collection to iterate over
 * @param {Function} callback Callback of each iteration, takes value and index
 * @param {Bool} [noCollect=false] Disable collecting of results
 * @returns {Promise} Promise resolved/rejected based on the iteration process (RTFM)
 */
function Mapromise(collection, callback, options = {}) {
	return new Promise(function(resolve, reject) {
		let iterator;
		const collector = options.collect ? [] : null;
 
		Iif (Reflect.has(collection, 'next')) iterator = collection;
		Eif (collection[Symbol.iterator]) iterator = collection[Symbol.iterator]();
		Iif (!iterator) return reject(new Error('Not iterable'));
 
		iterationStep(iterator, 0, callback, collector, (result) => resolve(result), (reason) => reject(reason));
	});
}
 
function iterationStep(iterator, index, callback, collector, resolve, reject) {
	let current = iterator.next();
	if (current.done) return resolve(collector || index);
 
	Promise.resolve(callback(current.value, index))
		.then((result) => {
			Iif (collector) collector.push(result);
			iterationStep(iterator, index + 1, callback, collector, resolve, reject);
		})
		.catch(reject);
}
 
module.exports = Mapromise;