Palindrome Checker

Palindrome Checker
0

#1

Hi, I’ve just completed the Palindrome Checker activity, however afterwards when I checked the solutions I noticed the recommended code. Would my solution be considered bad code?

function palindrome(str) {
  // Good luck!
  var removeSpecs = str.replace(/([^a-z0-9]+)/gi, '').toLowerCase();
  var strArray = removeSpecs.split("");
  var stripped = strArray.join("");
  var reversed = strArray.reverse().join("");
  
  
  if (stripped === reversed){
    return true;
  } else {
    return false;
  }
}


palindrome("Eyes");

#2

Your code has been blurred out to avoid spoiling a full working solution for other campers who may not yet want to see a complete solution. In the future, if you post a full passing solution to a challenge and have questions about it, please surround it with [spoiler] and [/spoiler] tags on the line above and below your solution code.

Thank you.

What makes you think your solution is considered bad code? It is fine for a first pass solution.

As far as improvements, you could first delete the following line:

var stipped = strArray.join("");

and then just compare reversed to removeSpecs in your if statement.

Another slight improvement would be to delete the else statement and simply return false after the if statement, because if true is not returned by the if statement, you know it must be false.

Lastly, if you really want to streamline the last part, look into the ternary operator which would replace your entire if/else code block by a single line of code.


#3

Thanks for your feedback. I need to accept that there is more than one way to solve a problem and any further efficiency will hopefully come with time.