Home > Software design >  I wrote a palindrome checking function. Why is it always returning true regardless of what string I
I wrote a palindrome checking function. Why is it always returning true regardless of what string I

Time:08-09

Every time I make changes after the first few lines no matter what I do the function is always true. I know there are other issues to address with checking for palindromes, but I'm just looking to fix whatever bug is causing this.

const palindromes = function (str) {
const arr = Array.from(str)
const arr2 = arr.reverse()



for (let i = 0; i < arr.length; i  ) {
    if (arr[i] !== arr2[i]){
    return false
    }
    else if (arr[i] === arr2[i] && i < (arr.length - 1)){
        continue
    }
    else {
        return true
    } 


}


};

CodePudding user response:

Arr.reverse() mutates the original arr object, that leads you to compare two of the same arrays.

CodePudding user response:

The function .reverse() reverses the array on which it is called, i.e it reverses inplace. Hence your variable arr gets reversed and gets compared with arr2 has the same value as arr.

Instead of const arr2 = arr.reverse() try const arr2 = arr.slice().reverse()

It will first create a copy of arr and then reverse it and store the variable in arr2

  • Related