Practice Set - Functions & Input Validation

by Rick Harraghy

HTML

<h3>Open the console to see the output from this code</h3>
<p>There are two exercises in this practice set</p>
<ol>
    <li>In the first, you must write the logMessage() function that will make the call on line 6 write the argument to the console. </li>
    <li>In the second, you will add input validation to this function so that the test cases work. If you've done it correctly, test cases 1-3 should output a truncated string (or the original, if the "targetLength" value is greater than the string length or is undefined) , while test cases 4 and 5 will output the string "Invalid Input".</li>
</ol>

JavaScript

/*  
#1
This code is calling on a function logMessage(), that should accpet a single parameter, and write that parameter to the console.  No input validation is required - just echo the parameter to the console. Write the logMessage() function so that this code works. 
*/
//simple fuction to log messages to the console
// accepts the message to log
// returns nothing
function logMessage(myMessage){
     console.log(myMessage);
}
var name = "Ellen Ripley";
logMessage("My name is "+ name);

/*
#2
The following function returns its string parameter trimmed to the length specified in the second parameter. If the parameters are not a string and an integer (or something convertible to a string and an integer), the function fails with an error. Modify this function so that if the input is invalid, it returns the string "Invalid input", otherwise it returns the truncated string.

For what counts as 'convertible to a number' or to a string, only the listed test cases need to be covered. You don't have to worry about other kinds of input like 'false' or '10c', etc 

*/
function truncate(inputString, targetLength){
    if (arguments.length == 2)
    {
        if ((typeof inputString == 'string' || inputString instanceof String) && (typeof targetLength == 'number'))
        {
            return inputString.substr(0, targetLength);;
        }
        else
        {
            return "Invalid Input";
        }
    }
    else if (arguments.length == 1)
    {
        if ((typeof inputString == 'string' || inputString instanceof String))
        {
            //Assume first variable (inputString) entered and return it
            return inputString;
        }
        else
        {
            return "Invalid Input";
        }
    }
    else  //(arguments.length == 0 or > 2)
    {
        return "Invalid Input";
    }    
}

//test cases 
var x = "Fourscore and seven years ago";
var y;
console.log("1: " + truncate(x, 10));
console.log("2: " + truncate(x));    // should output...