-2

I have tried to make this palindrome checker but it sometimes returns the right answer and sometimes not. Please tell me the bugs in this code... I know that there are more efficient ways to make a palindrome checker but for learning purposes I want to know what is wrong with mine...

function palindrome(str) {
  var newString;
  //convert string to lower-case
  var strLowerCase = str.toLowerCase();
  //Find string length
  var strLength = str.length;
  //replace first 1/2 with second 1/2
  newString = replaceLetters(strLowerCase,strLength);
  if(newString === strLowerCase){
    return true;
  }else{
    return false;
  }
}

function replaceLetters(string,length){
  var x;
  for(var a = 0; a<Math.ceil(length/2) ; a++){
    x = string.replace(string.charAt(a),string.charAt(length-1));
    length--; 
  }
  return x;
}


palindrome("eye");
smoggers
  • 3,154
  • 6
  • 26
  • 38
  • You should show us what is wrong with the result by giving examples of the actual output and the expected output. – Andrew Morton Nov 28 '15 at 15:13
  • http://stackoverflow.com/help/how-to-ask – AK_ Nov 28 '15 at 15:14
  • 1
    Seems to be working fine for me... I've tried a number of inputs with odd and even amount of letters. On what input do you get unexpected results? – Chizzle Nov 28 '15 at 16:10
  • should provide some input for any failures..in case you want to learn a better way to write a method for palindrome verification then http://stackoverflow.com/questions/22111507/how-to-write-palindrome-in-javascript would help you(+1 AK) – Naman Nov 28 '15 at 16:16

1 Answers1

0

You shouldn't pass the str length as a parameter. Just make a variable length from str.length - 1 in replaceLetters. Also you want math.floor not math.ceil. let's say for a 9 letter words, you only want to swap the first 4 chars not the first 5. You don't need to swap the middle char which is the 5th.Ex: Racecar, you don't swap e with anything to check if its palindrome. You can also use the splice function instead of making your own replace letters function. Some other knitpicking, what's the point of making the strlowercase var since your only calling to lowercase() once?

Daniel Kobe
  • 9,376
  • 15
  • 62
  • 109