Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

The only word that is not passing the test is "almostomla."

I am learning JS on freecodecamp and am stuck on a problem. I am creating a palindrome checker. My code almost works. However, there is only one word that is not passing the test and that is almostomla. It is not a palindrome yet my code returns true. I have tried several things. Even rewrote the code and used the while loop but nothing seems to help. There is a solution at the freeCodecamp web but I have written the code in a different way and am unable to figure my mistake out.

Here is my code.

let reversedStr = [];

function palindrome(str) {
  let d = str.replace(/[^a-zA-Z0-9]/g, "").toLowerCase();
  for (let i = d.length - 1; i >= 0; i--) {
    reversedStr.push(d[i]);
  }
  for (let j = 0; j < str.length; j++) {
    if (reversedStr[j] == d[j]) {
      return true;
    } else {
      return false;
    }
  }
}
console.log(palindrome("almostomla"));

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

This line if (reversedStr[j] == d[j]) {return true; returns as soon as the character matches at both the index. It does not check rest of the characters.

In fact you can just return as soon as the character in both index does not match.

Also note the reversedStr has to be inside the function. Else it will contain previous values

function palindrome(str) {
  let reversedStr = [];
  let d = str.replace(/[^a-zA-Z0-9]/g, "").toLowerCase();
  for (let i = d.length - 1; i >= 0; i--) {
    reversedStr.push(d[i]);
  }
  
  for (let j = 0; j < str.length; j++) {
    if (reversedStr[j] !== d[j]) {
      return false;
    }
  }
  return true
}
console.log(palindrome("almostomla"));
console.log(palindrome("1221"));
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading