// controller function
const getValues = () => {
// get the user's input
let userInput = document.getElementById("message").value;
// send it through the reversed string function
const palindromeInfoArray = checkForPalindrome(userInput);
displayResults(palindromeInfoArray);
};
// business logic
const checkForPalindrome = (message) => {
// declare empty string
if (message == '') message = `Nothing at all`
let reversedStr = "";
let inputStr = message.replace(/[^a-zA-Z0-9]/g, '').toLowerCase();
const output = [message];
for (let i = inputStr.length - 1; i >= 0; i--) {
reversedStr += inputStr[i];
}
output.push(reversedStr, reversedStr == inputStr);
return output;
};
// view function
const displayResults = (array) => {
// display string on the page
if (array[2] == true) {
// congrats message
document.getElementById("failure-alert").classList.add("d-none");
document.getElementById("success-message").textContent = `"${array[0]}" written backwards is ${array[1]}! You've got yourself a palindrome.`;
document.getElementById("success-alert").classList.remove("d-none");
} else {
// too bad message
document.getElementById("success-alert").classList.add("d-none");
document.getElementById("failure-message").textContent = `${array[0]} written backwards is ${array[1]} which is not a palindrome.`;
document.getElementById("failure-alert").classList.remove("d-none");
}
};
There are three key functions that make this program run properly:
getValues
this function searches our HTML by ID for a corresponding string of text that the user entered
checkForPalindrome
This is where the magic happens. Regex is used to ignore all characters besides numbers and letters. the string is reversed, and then simply compared to the original string. It's important to change the string to lowercase so that all letters are treated equally.
displayResults
this function is here to show off the output onto the website for the user, but it also is responible for deciding whether to give a success message or a failure message based on the array of information provided in its parameters.
Together, these functions keep each piece of complexity separate, so that it is easy to read, understand, and manipulate.