DEV Community

loading...

Discussion on: Daily Challenge #214 - Persistent Bugger

Collapse
aminnairi profile image
Amin • Edited

TypeScript

"use strict";

/**
 * Compute the multiplicative persistence of a number.
 * 
 * @param {number} number The number to compute the persistence from.
 * 
 * @throws {Error}      If the function is called with not exactly one argument.
 * @throws {TypeError}  If the first argument is not an integer.
 * @throws {RangeError} If the first argument is not greater than or equal to zero.
 * 
 * @return {number} The persistence of the number.
 * 
 * @example
 * persistence(39);     // 3
 * persistence(999);    // 4
 * persistence(4);      // 0
 */
const persistence = (number: number, ...extraParameters: unknown[]): number => {
    if (0 !== extraParameters.length) {
        throw new RangeError("The function has not been called with exactly one argument.");
    }

    if (!Number.isInteger(number)) {
        throw new TypeError("First argument is not an integer.");
    }

    if (0 > number) {
        throw new RangeError("First argument is not greater than or equal to zero");
    }

    const characters = number.toString();

    if (1 === characters.length) {
        return 0;
    }

    return 1 + persistence([...characters].reduce((total, character) => total * parseInt(character), 1));
};
Collapse
molamk profile image
molamk

Nice 👌