diff --git a/apps/palindrome-checker/public/script.js b/apps/palindrome-checker/public/script.js index 549fdc5ad..d5272bd7c 100644 --- a/apps/palindrome-checker/public/script.js +++ b/apps/palindrome-checker/public/script.js @@ -2,39 +2,54 @@ const userInput = document.getElementById('text-input'); const checkPalindromeBtn = document.getElementById('check-btn'); const resultDiv = document.getElementById('result'); -const checkForPalindrome = input => { - const originalInput = input; // Store for later output - - if (input === '') { - alert('Please input a value'); - return; - } +// Normalize text by removing non-alphanumeric characters and lowercasing +const normalizeText = str => + str.replace(/[^A-Za-z0-9]/gi, '').toLowerCase(); + +// Return true if the given text is a palindrome +const isPalindrome = str => { + const normalized = normalizeText(str); + return normalized === [...normalized].reverse().join(''); +}; +const showResultMessage = message => { // Remove the previous result resultDiv.replaceChildren(); - const lowerCaseStr = input.replace(/[^A-Za-z0-9]/gi, '').toLowerCase(); - let resultMsg = `${originalInput} ${ - lowerCaseStr === [...lowerCaseStr].reverse().join('') ? 'is' : 'is not' - } a palindrome.`; - const pTag = document.createElement('p'); pTag.className = 'user-input'; - pTag.innerText = resultMsg; + pTag.textContent = message; resultDiv.appendChild(pTag); - // Show the result. + // Show the result resultDiv.classList.remove('hidden'); }; -checkPalindromeBtn.addEventListener('click', () => { +const checkForPalindrome = rawInput => { + const originalInput = rawInput; // Preserve for output + const input = rawInput.trim(); + + if (!input) { + showResultMessage('Please input a value.'); + return; + } + + const resultMsg = `${originalInput} ${ + isPalindrome(input) ? 'is' : 'is not' + } a palindrome.`; + + showResultMessage(resultMsg); +}; + +const handleCheck = () => { checkForPalindrome(userInput.value); userInput.value = ''; -}); +}; + +checkPalindromeBtn.addEventListener('click', handleCheck); userInput.addEventListener('keydown', e => { if (e.key === 'Enter') { - checkForPalindrome(userInput.value); - userInput.value = ''; + handleCheck(); } -}); +}); \ No newline at end of file