The Code for REWIND
// Retrieve user input
// Controller function
function getString() {
document.getElementById("alert").classList.add("invisible");
let userInput = document.getElementById("userString").value;
let reversedString = reverseString(userInput);
displayString(reversedString);
}
// Reverse the string
// Logic function
function reverseString(userInput) {
let characters = [];
// Reverse the string using a for loop
for (let i = userInput.length - 1; i >=0; i--)
{
characters += userInput[i];
}
return characters;
}
// Display the result
// View function
function displayString(reversedString) {
// Write to the page
document.getElementById("msg").innerHTML = `Your string reversed is: ${reversedString}`;
// Show the alert box
document.getElementById("alert").classList.remove("invisible");
}
getString()
This is the controller function that will call the other functions I defined to help make the code easier to read. First, it ensures that the alert box is hidden. Then, it gets the userString and assigns it to the variable userInput. After that, it calls reverseString() with userInput as the argument, and assigns the result to the variable reversedString. Finally, it calls displayString() with reversedString as its argument.
reverseString()
First, this function declares an array named characters. This array will store each individual character from the string userInput. Then, using a for loop, I iterate through userInput starting from the last character, and on each iteration it adds that character to the array characters. Once the loop is finished, we return the array.
displayString()
This function takes the reversedString variable and modifies the DOM to show the alert box with a message and the result.