DEV Community

Discussion on: Daily Challenge #88 - Recursive Ninjas

Collapse
 
aminnairi profile image
Amin • Edited

JavaScript

Decided to throw an error if the count is not greater than zero because a ninja won't bother spending energy on calling this secret technique for no purposes.

"use strict";

/**
 * Ninja secret call sound function
 * 
 * @param {number} count The number of times the word "chirp" should be repeated
 * @throws If the argument count is not valid
 * @throws If the first argument is not a number
 * @throws If the first argument is not greater than 0
 * @return {string} The ninja secret call sound
 * @example chirp(15);
 */
function chirp(count) {
    if (arguments.length !== 1) {
        throw new Error("Expected exactly one parameter.");
    }

    if (typeof count !== "number") {
        throw new TypeError("First argument expected to be a number.");
    }

    if (count <= 0) {
        throw new Error("First argument expected to be greater or equal to 1.");
    }

    if (count === 1) {
        return "chirp.";
    }

    const decreasedCount = count - 1;

    return `chirp-${chirp(decreasedCount)}`;
}

console.log(chirp(4));
console.log(chirp(3));
console.log(chirp(2));
console.log(chirp(1));
console.log(chirp(0));

Training dojo available here (say chirp to enter).