"use strict";/**
* Find the index of an element in an array
* @param {unknown} element Element to search
* @param {unknown[]} elements Elements in which to search from
* @param {number} position Starting position (default to 0)
* @throws {TypeError} If the second argument is not an array
* @throws {TypeError} If the third argument is not an integer
* @throws {RangeError} If the third argument is lower than zero
* @return {number} -1 if the element is not found, the index otherwise
* @example index(1, [-1, 0, 1, 2, 3]); // 2
* @example index(2, [-1, 0, 1, 2, 3]); // 3
* @example index(5, [-1, 0, 1, 2, 3]); // -1
*/functionindex(element,elements,position=0){if(!Array.isArray(elements)){thrownewTypeError("Expected second argument to be an array");}if(!Number.isInteger(position)){thrownewTypeError("Expected integer for the third argument");}if(position<0){thrownewRangeError("Expected third argument to be greater or equal to zero");}if(elements.length===0){return-1;}/**
* @const {unknown} current The first elements of the array
* @const {unknown} rest All elements except the first one
*/const[current,...rest]=elements;if(current===element){returnposition;}returnindex(element,rest,position+1);}console.log(index(1,[-1,0,1,2,3]));// 2console.log(index(2,[-1,0,1,2,3]));// 3console.log(index(5,[-1,0,1,2,3]));// -1
Recursive solution with runtime type checking.
Woah, interesting...