DEV Community

Discussion on: Daily Challenge #206 - Pound Means Backspace

Collapse
 
aminnairi profile image
Amin

JavaScript

/**
 * Remove backspaces from a string
 * @param {String} string
 * @throws {Error} If the function gets called with more or less than one argument
 * @throws {TypeError} If the function gets called with a non-string argument
 * @return {String}
 */
function cleanString(string) {
    if (arguments.length !== 1) {
        throw new Error("Expected exactly one argument.");
    }

    if (typeof string !== "string") {
        throw new TypeError("Expected first argument to be a string.");
    }

    const characters = [];

    for (const character of string) {
        // If this is a character
        if (character !== "#") {
            characters.push(character);

            continue;
        }

        // If this is a backspace character
        // And that there is at least one character 
        if (characters.length) {
            characters.pop();
        }
    }

    return characters.join("");
}