0

I need help with this palindrome assignement (should show true for words which are the same read from behind, regardless of spaces, symbols and punctuation). I don't see a problem here , but it's not working properly. Problems are like regex is not ok, but I tested regex on regexr and it should be ok.

Anyone sees what the problem is ?

Thanks in advance.

function palindrome(str) {

  var pal = str;

  pal.replace(/[\W_]/g, "");
  pal.toLowerCase();

  var arr = pal.split("");
  arr.reverse();
  var pal2 = arr.join("");

  if(pal2 === pal){
    return true;
  }
  else{
    return false;
  }

}


//this should show true but its false
palindrome("_eye");
Perp
  • 364
  • 7
  • 15

1 Answers1

0

Like I said in the comment, your code doesn't work because it assumes both replace() and toLowerCase() augment their argument. But they don't, they return a new string instead of modifying the given one. So in your example _ symbol is still there in the comparing routine, messing up the expected result.

Another sidenote: when you base the result of a function on some comparison operation, there's no need to use if. You can always replace this:

if (a === b) {
  return true;
}
else {
  return false;
}

... with simple:

return a === b;

Speaking about the task in general: while split-reverse-join-compare is the easiest approach (check @adeneo's comment for a nice one-liner), it's not optimal. Think about it: you only need to compare the halves of the string against each other. There's one way to do it:

function isDirectPalindrome(str) {
  var i = 0, j = str.length - 1;
  while (i < j) {
    if (str.charAt(i++) !== str.charAt(j--)) {
      return false;
    }
  }
  return true;
}

function isPalindrome(str) {
  return isDirectPalindrome(str.replace(/[\W_]+/g, '').toLowerCase());
}

There are two functions here: the first one always checks whether the string's a palindrome as is (no 'noise' symbols here), the second one normalizes a string beforehand. This makes it more simple to reuse the first one whenever you need it.

Of course, it's just a test. But I think it's convenient - and useful - to show both algorithms and modularity points here.

raina77ow
  • 103,633
  • 15
  • 192
  • 229