Topic Description

Implement a findIndex function from scratch. It should accept three parameters:

The findIndex function should return the index of the first element in the array that satisfies the predicate function. If no elements satisfy the condition, it should return -1.

// Examples
console.log(findIndex([1, 13, 7, 54], (num) => num > 10)); // 1
console.log(findIndex([1, 13, 7, 54], (num) => num > 200)); // -1

Answer

function findIndex(array, predicate, fromIndex=0){
	let resultIndex = -1 
	if(array.length ==0){
		return resultIndex
	}
	const startIndex = fromIndex < 0 ? fromIndex + array.length : fromIndex
	for(let i = startIndex; i < array.length; i++){
		if( predicate(array[i]) ){
			resultIndex = i
			break
		}
	}
	
	return resultIndex
}