Week 5 Assignment 1
Part 1 and 2
by Larry Adams
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.
<h2 id="q1"></h2></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 isn't greater than the string length) , while test cases 4 and 5 will output the string "Invalid Input".
<h2>Answer(s):</h2>
<p id="1"></p>
<p id="2"></p>
<p id="3"></p>
<p id="4"></p>
<p id="5"></p>
</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.
*/
console.clear();
var name = "Ellen Ripley";
function logMessage(myName) {
console.log(myName);
document.getElementById("q1").innerHTML = name;
}
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(typeof inputString == 'String' && typeof targetLength == 'Number') {
return inputString.substr(0, targetLength);
}else if (typeof inputString == 'undefined') {
return 'Invalid Input';
} else if (isNaN(parseInt(targetLength))) {
return 'Invalid Input';
} else if (typeof inputString == 'string') {
return inputString.substr(0, targetLength);
} else {
return targetLength;
}
}
//test cases
var x = "Fourscore and seven years ago";
var y;
console.log("1: " + truncate(x, 10));
document.getElementById("1").innerHTML = "1: " + truncate(x, 10);
console.log("2: " + truncate(x)); // should output the unmodified string
document.getElementById("2").innerHTML = "2: " + truncate(x);
console.log("3: " +...