All files async-reduce.js

100% Statements 16/16
100% Branches 3/3
100% Functions 1/1
100% Lines 16/16

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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        1x 1x                             12x 11x   10x 10x   10x 3x 3x   1x         2x 2x     9x   400x     8x     1x  
const {
		validateIsIterable,
		validateIsFunction,
		validateNonZeroLength
	} = require('./validation'),
	{ noParam } = require('./constants');
 
/**
 * Async Reduce
 *
 * Reduce asynchronously and resolve when
 * all items have been transduced.
 * @async
 * @param {any[]} iterable
 * @param {Function} callback - callback(accumulator, currentValue, index, array)
 * @param {any} [accumulator=noParam]
 * @return {Promise<any>}
 * @throws {TypeError}
 */
async function asyncReduce(iterable, callback, accumulator = noParam) {
	validateIsIterable(iterable);
	validateIsFunction(callback);
 
	const length = iterable.length;
	let i = 0;
 
	if (accumulator === noParam) {
		try {
			validateNonZeroLength(iterable);
		} catch (e) {
			throw new TypeError(
				'asyncReduce of empty array with no accumulator given'
			);
		}
 
		accumulator = iterable[0];
		i = 1;
	}
 
	for (; i < length; i++) {
		// eslint-disable-next-line no-await-in-loop
		accumulator = await callback(accumulator, iterable[i], i, iterable);
	}
 
	return accumulator;
}
 
module.exports = { asyncReduce };