Skip to content

Instantly share code, notes, and snippets.

@chubuntuarc
Created September 18, 2020 00:12
Show Gist options
  • Save chubuntuarc/685c92ee66232eef90f9c91750fea0de to your computer and use it in GitHub Desktop.
Save chubuntuarc/685c92ee66232eef90f9c91750fea0de to your computer and use it in GitHub Desktop.
Jesus Arciniega SP
//Review if is a palindrome.
let input = 'Anita lava la tina';
//let input = 'alla';
//let input = "Aranara";
//let input = "aAranar";
//Function to review if a string is palindrome
function isPalindrome(text){
try {
//Create an array from the String.
text = text.replace(/[\W_]/gi, "").toLowerCase(); //Clean the string.
let array = text.split("");
//Array of unique chars.
let uniqueValues = [...new Set(array)];
//Review if the string has no duplicates.
/*Review the length of the arrays, if is the same, then don't have any duplicated value.*/
hasDuplicates = uniqueValues.length === array.length ? false : true;
if (!hasDuplicates) {
//Any duplicated char, then is not palindrome
return `${text} Isn't a palindrome`;
}
//If is a single letter word
if (array.length === 1) return `${text} Is a palindrome`;
//Direct validation.
//Review if the text is the same in reverse.
let reversedText = array.reverse().join("");
if (reversedText === array) {
return `${text} Is a palindrome`;
}
//Review if the direct validation doesn't work.
//Review if has more than one odd value.
let oddCounter = 0;
//This is the main idea that i try in the interview.
uniqueValues.forEach((char) => {
//Review the unique values in the original array.
let charsCounter = array.filter((value) => value === char).length;
if (charsCounter % 2 !== 0) oddCounter++;
});
if (oddCounter > 1) return `${text} Isn't a palindrome`;
return `${text} Is a palindrome`;
} catch (error) {
//Review errors if exists.
console.log(`isPalindrome :: ${error}`);
return `${text} Isn't a palindrome`;
}
}
console.log(isPalindrome(input));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment