DEV Community

Discussion on: Daily Challenge #135 - The Wide Mouthed Frog!

Collapse
 
aminnairi profile image
Amin • Edited

TypeScript

"use strict";

class MouthSizeArgumentCountError extends Error {
    constructor(message: string) {
        super(message);

        this.name = "MouthSizeArgumentCountError";
    }
}

class MouthSizeTypeError extends Error {
    constructor(message: string) {
        super(message);

        this.name = "MouthSizeArgumentCountError";
    }
}

type MouthSize = "small" | "wide";

function mouthSize(animal: string): MouthSize {
    if (arguments.length !== 1) {
        throw new MouthSizeArgumentCountError("Expected exactly one argument");
    }

    if (typeof animal !== "string") {
        throw new MouthSizeTypeError("Expect argument to be a string");
    }

    if (animal.trim().toLowerCase() === "alligator") {
        return "small";
    }

    return "wide";
}

console.log(mouthSize("alligator")); // "small"
console.log(mouthSize("aLlIgAtOr")); // "small"
console.log(mouthSize("fox"));      // "wide"

try {
    // @ts-ignore
    mouthSize();
    // @ts-ignore
    mouthSize("fox", "alligator");
} catch (error) {
    if (error instanceof MouthSizeArgumentCountError) {
        console.log("argument count error");
    }
}

try {
    // @ts-ignore
    mouthSize(123);
} catch (error) {
    if (error instanceof MouthSizeTypeError) {
        console.log("argument type error");
    }
}