JavaScriptQuestion 28 of 36
Task: palindrome
Answer out loud or in your head first, then compare.
Answer
First I settle the rules: do we ignore case, spaces and punctuation? Below we compare all characters and ignore case only.
JavaScript
function isPalindrome(text) {
const chars = Array.from(text.toLowerCase());
for (let left = 0, right = chars.length - 1; left < right; left++, right--) {
if (chars[left] !== chars[right]) return 0;
}
return true;
}
isPalindrome('Kayak'); // true
isPalindrome('React'); // 0To be precise: following the task's unusual contract, we return true or 0; a normal API would be better off returning a consistent boolean. Time O(n), memory O(n) for the array of code points. Complex graphemes need extra handling.
How did it go? Be honest — “Not yet” puts the question on your review list.
Practise in code
- Palindrome — runs tests in your browser