DEV Community

loading...

Discussion on: What’s your alternative solution? Challenge #12

Collapse
aminnairi profile image
Amin

My take at the challenge using recursion.

/**
 * Takes only positives values from an array
 *
 * @params {number[]} numbers Numbers's array
 *
 * @throws {Error}      If the function is not called with one argument
 * @throws {TypeError}  If the first argument is not an array
 * @throws {TypeError}  If the first argument is not an array of numbers
 *
 * @return {number[]} Positives numbers
 *
 * @example
 * positivesOnly([-1, 1, -2, 2]);   // [1, 2]
 * positivesOnly([1, 2]);           // [1, 2]
 * positivesOnly([-1, -2]);         // []
 */
const positivesOnly = (numbers, ...extraParameters) => {
    if (extraParameters.length !== 0) {
        throw new Error("expected one argument");
    }

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

    if (numbers.length === 0) {
        return [];
    }

    const [number, ...rest] = numbers;

    if (typeof number !== "number") {
        throw new TypeError("expected first argument to be an array of numbers");
    }

    if (number < 0) {
        return positivesOnly(rest);
    }

    return [number, ...positivesOnly(rest)];
};
Forem Open with the Forem app