DEV Community

loading...

Discussion on: Daily Challenge #124 - Middle Me

Collapse
aminnairi profile image
Amin • Edited

TypeScript

Assuming we only accept one character for the middle and the surrounding.

"use strict"

/**
 * Surround a character with some more character N times
 * 
 * @param {string} middleCharacter The character to insert in the middle of the string
 * @param {string} surroundingCharacters The character that will surround the middle one
 * @param {number} repeatCount The number of times the surrounding character will be repeated
 * @throws {Error} If the argument count is not three
 * @throws {TypeError} If the first argument is not a string
 * @throws {TypeError} If the second argument is not a string
 * @throws {TypeError} If the third argument is not a number
 * @throws {TypeError} If the first argument has a length different than one
 * @throws {TypeError} If the second argument has a length different than one
 * @throws {TypeError} If the third argument is lower than one
 * @return {string} The middle character with its surrounding characters
 */
function middleMe(middleCharacter: string, surroundingCharacters: string, repeatCount: number): string {
    if (arguments.length !== 3) {
        throw new Error("Three arguments expected")
    }

    if (typeof middleCharacter !== "string") {
        throw new TypeError("First argument expected to be a string")
    }

    if (typeof surroundingCharacters !== "string") {
        throw new TypeError("Second argument expected to be a string")
    }

    if (typeof repeatCount !== "number") {
        throw new TypeError("Third argument expected to be a string")
    }

    if (middleCharacter.length !== 1) {
        throw new Error("First argument must have a length of one")
    }

    if (surroundingCharacters.length !== 1) {
        throw new Error("Second argument must have a length of one")
    }

    if (repeatCount < 1) {
        throw new Error("Third argument must be greater or equal to one")
    }

    if (repeatCount % 2 !== 0) {
        return middleCharacter
    }

    const computedSurroundingCharacters: string = surroundingCharacters.repeat(repeatCount / 2)

    return `${computedSurroundingCharacters}${middleCharacter}${computedSurroundingCharacters}`
}

Playground

Repl.it.