Skip to content

Instantly share code, notes, and snippets.

@jherax
Last active January 5, 2020 13:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save jherax/b72b2fc89efb73ce5100c0bccbf04ba3 to your computer and use it in GitHub Desktop.
Save jherax/b72b2fc89efb73ce5100c0bccbf04ba3 to your computer and use it in GitHub Desktop.
Determines whether a string is a palindrome
/**
* Determines whether a text is a palindrome.
* Text is lowercased and non-alphabetic characters are removed.
*
* @param {string} text - the words to check
* @return {boolean}
*/
function isPalindrome(text) {
if (!text || text.length < 2) return false;
text = text.replace(/[\s\W]/g, '');
const chars = text.toLowerCase().split('');
let left = 0,
right = chars.length - 1;
while (chars[left] === chars[right] && left < right) {
left += 1;
right -= 1;
}
return left === right || left > right;
}
isPalindrome(); // false
isPalindrome('Y'); // false
isPalindrome('Ana'); // true
isPalindrome('aaabbb'); // false
isPalindrome('aaoooocc'); // false
isPalindrome('Civic'); // true
isPalindrome('Madam'); // true
isPalindrome('Rotator'); // true
// it removes spaces to compare characters only
isPalindrome('Top spot'); // true
isPalindrome('Step on no pets'); // true
isPalindrome('anita lava la tina'); // true
// it removes non-alphabetic characters in order to compare
isPalindrome('Eva, can I see bees in a cave?'); // true
isPalindrome('Are we not drawn onward to new era?'); // true
@subversivo58
Copy link

How exactly does this return true?

isPalindrome('aaoooocc'); //true

ES6

let isPalindrome = (str) => (str === str.split('').reverse().join('')) ? true : false

// test
console.log(
    isPalindrome('aaabbb'),
    isPalindrome('aaoooocc'),
    isPalindrome('anitalavalatina')
)
// false false true

@jherax
Copy link
Author

jherax commented Jul 5, 2019

How exactly does this return true?

isPalindrome('aaoooocc'); //true

ES6

let isPalindrome = (str) => (str === str.split('').reverse().join('')) ? true : false

// test
console.log(
    isPalindrome('aaabbb'),
    isPalindrome('aaoooocc'),
    isPalindrome('anitalavalatina')
)
// false false true

@subversivo58 Yes, it is wrong, I wrote it again from scratch, now it is more concise and shorter :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment