All files async-find-index.js

100% Statements 12/12
100% Branches 3/3
100% Functions 5/5
100% Lines 10/10

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 381x 1x                           11x 10x   9x       8x     420x   420x       94x         1x  
const { mapIterable } = require('./helpers'),
	{ validateIsIterable, validateIsFunction } = require('./validation');
 
/**
 * Async Find Index
 *
 * Find an item's index asynchronously and resolve when found or all callbacks resolve
 * @async
 * @param {any[]} iterable
 * @param {Function} callback - callback(currentValue, index, array)
 * @param {any} [thisArg=undefined]
 * @return {Promise<Number>} - an integer index, -1 if not found
 * @throws {TypeError}
 */
async function asyncFindIndex(iterable, callback, thisArg = undefined) {
	validateIsIterable(iterable);
	validateIsFunction(callback);
 
	const tasks = mapIterable(iterable, callback.bind(thisArg), {
		useEmptyElements: true
	});
 
	return Promise.race([
		Promise.race(
			tasks.map(async (task, index) => {
				const checkIsFound = await task;
 
				return new Promise(resolve => checkIsFound && resolve(index));
			})
		),
		Promise.all(tasks).then(taskResults =>
			taskResults.findIndex(result => result)
		)
	]);
}
 
module.exports = { asyncFindIndex };