DEV Community

Discussion on: Daily Challenge #220 - What Dominates Your Array?

Collapse
 
aminnairi profile image
Amin • Edited

JavaScript

/**
 * Return the integer that occurs more than half of the size of an array
 *
 * @param {number[]} numbers The array of integers.
 *
 * @throws {Error}      If the function gets called with not exactly one argument.
 * @throws {TypeError}  If the first argument is not an array.
 * @throws {TypeError}  If the first argument is not an array of integers.
 *
 * @return {number} -1 if there is no dominator
 *
 * @example
 * console.log(dominator([3,4,3,2,3,1,3,3]));  // 3
 * console.log(dominator([1,1,1,2,2,2]));      // -1
 * console.log(dominator([1,1,1,2,2,2,2]));    // 2
 */
function dominator(numbers) {
    if (arguments.length !== 1) {
        throw new Error("Expected one argument.");
    }

    if (!Array.isArray(numbers)) {
        throw new TypeError("Expected first argument to be an array.");
    }

    const occurrences   = {};
    const threshold     = numbers.length / 2;

    for (const number of numbers) {
        if (!Number.isInteger(number)) {
            throw new TypeError("Expected first argument to be an array of integers.");
        }

        if (occurrences[number]) {
            occurrences[number]++;
        } else {
            occurrences[number] = 1;
        }

        if (occurrences[number] > threshold) {
            return number;
        }
    }

    return -1;
}