I built a small JavaScript function to see if a series of characters are a palindrome or not. The functions works well and does everything it has to do, but I'm wondering if something can be tweaked to make it faster.
This is the actual code:
var words = ['anita lava la tina',' a ', 'civvic', 'ddaa', 'aa', 'dca', '332', null, 'toyota','racecar'];
function getPalindrome(word){
if(!word || (word = word.replace(/ /g,'')).length<2)
return "-1";
var charsCount = {};
word = word.toLowerCase();
var chars = word.split("");
//ahorra un poco de tiempo cuando las palabras son grandes
if(chars.reverse().join('')===word)
return word;
for(var i=0;i<chars.length;i++){
if(charsCount[chars[i]])
charsCount[chars[i]] += 1;
else
charsCount[chars[i]] = 1;
}
//si hay mas de un impar, ya no puede ser palindromo
var oddCounter = 0;
var palindromo = [];
var oddChar = '';
for(var letter in charsCount){
if(charsCount[letter] % 2 !== 0)
oddCounter++;
if(oddCounter>1)
return "-1";
var times = charsCount[letter];
if(times===1){
oddChar = letter;
}
else{
for(var i=0;i<times;i++){
if(i%2==0)
palindromo.push(letter);
else
palindromo.unshift(letter);
}
}
}
//agrego el impar a la mitad, si es que hay
palindromo.splice(palindromo.length/2,0,oddChar);
return palindromo.join('');
}
for(var i in words){
console.log(words[i],":",getPalindrome(words[i]));
}
What I do here is this:
- If
word
is null or the length ofword
after eliminating spaces is lower than 2, then it's not a palindrome, so return -1. - If the reverse of
word
equalsword
, then it is a palindrome, so return the word. - Make a map with all the chars, adding the occurrence of each char.
- Loop the map of the chars: if the count of more than one char is an odd number, then it's not a palindrome, so return -1.
- Simply put one char at the beginning of an array and one at the end and loop n times if the char was found.
- Store the odd char in a variable for later use.
- When
loop (4)
ends, insert the odd char in the middle of the array. - Return the built palindrome.
The function works, but how can I make it faster?
word.split("").reverse().join("")===word
or am I missing something here. Your other checks seem pointless? \$\endgroup\$