DEV Community

Discussion on: #7DaysJS: Where is My Element

Collapse
 
aminnairi profile image
Amin

Recursive solution with runtime type checking.

"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
 */
function index(element, elements, position = 0) {
    if (!Array.isArray(elements)) {
        throw new TypeError("Expected second argument to be an array");
    }

    if (!Number.isInteger(position)) {
        throw new TypeError("Expected integer for the third argument");
    }

    if (position < 0) {
        throw new RangeError("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) {
        return position;
    }

    return index(element, rest, position + 1);
}

console.log(index(1, [-1, 0, 1, 2, 3])); // 2
console.log(index(2, [-1, 0, 1, 2, 3])); // 3
console.log(index(5, [-1, 0, 1, 2, 3])); // -1
Collapse
 
lautarolobo profile image
Lautaro Lobo

Woah, interesting...