The Code for REVERSO
// CONTROLLER FUNCTION(S)
// Get string from the page
function getString() {
let userString = document.getElementById("userString").value;
let revString = reverseString(userString);
document.getElementById("alert").classList.add("invisible");
// if input string is valid, then display reversed string
if (validateString(userString)) {
displayString(revString);
}
}
// LOGIC FUNCTION(S)
// Reverse the string
function reverseString(uString) {
let revString = [];
// reverse a string using a for loop
for (let index = uString.length - 1; index >= 0; index--) {
revString += uString[index];
}
return revString;
}
function validateString(uString) {
let output = true;
// check if string is empty or has only white spaces
if (uString.length === 0 || !uString.trim()) {
alert("Please enter a string for REVERSO!")
output = false;
}
return output;
}
// VIEW FUNCTION(S)
// Display the reversed string to the user
function displayString(rString) {
// write message to page
document.getElementById("msg").innerHTML = `${rString} !`;
// show the alert box
document.getElementById("alert").classList.remove("invisible");
}
The Code is structured in four functions.
getString
getString retrieves the user input string from the page. It utilises getElementById to get this string. A new string is declared, which is set to the output of the reverseString method, where the input string is reversed. A class of "invisible" is added to the alert div, so that the div is no visible when text is being updated or if the input is not valid. The input string is validated with the validateString function, and if this function returns a boolean value of true then the displayString function is executed with an input value of the reversed string.
reverseString
reverseString returns a string value which is the reverse of the string fed into the function. This is achieved with a 'for' loop which runs backwards from the last index of the input array to 0 (last index is the array length -1, since js array indices start from 0). On each iteration of the loop, the char is added to a new array called revString, which is returned after the loop completes.
validateString
The user input string is fed into this function, which checks to see if the string length is equal to 0 or formed entirely of white spaces. If either of these conditions evaluate to true, then a boolean variable named output is set to false, and an alert box notifies the user to input a string. The output variable is then returned.
displayString
The displayString function accepts a string input, which should be the reversed string, and displays the string to the paragraph of id msg in the alert div. The alert div then has the class of "invisible" removed so that the output is visible to the user.