Attempt 1 →

/*
  Implement a function `isPalindrome` which takes a string as argument and returns true/false as its result.
  Note: the input string is case-insensitive which means 'Nan' is a palindrom as 'N' and 'n' are considered case-insensitive.
*/

function palindrome(str) {
  let left = 0;
  let right = str.length - 1;
  let flag = 0;

  while (left < right) {
    if (str[left] != str[right]) {
      console.log(str[left] + " NOT EWUAL " + str[right]);
      flag++;
      break;
    }
    left++;
    right--;
  }
  return flag;
}

function isPalindrome(str) {
  if (str.length === 0) {
    return true;
  } else {
    if (str.split(" ").length > 0) {
      arr = str.split(" ");
      newStr = "";
      for (let i = 0; i < arr.length; i++) {
        newStr = newStr + arr[i];
      }
      lower_str = newStr.toLowerCase();
    } else {
      lower_str = str.toLowerCase();
    }
    console.log(lower_str);

    flag = palindrome(lower_str);

    if (flag != 0) {
      return false;
    }
    return true;
  }
}

module.exports = isPalindrome;

let str = "A man a plan a canal Panama";
let ans = isPalindrome(str);
console.log(ans);
console.log(str.split(" ").length);
console.log(str.split(" "));

Problems →

  1. It won’t return the correct output for strings with special characters

Final answer →

function palindrome(str) {
  let left = 0;
  let right = str.length - 1;
  let flag = 0;

  while (left < right) {
    if (str[left] != str[right]) {
      console.log(str[left] + " NOT EWUAL " + str[right]);
      flag++;
      break;
    }
    left++;
    right--;
  }
  return flag;
}

function isStrWithSpecialChar(str) {
  var format = /[!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]+/;
  // return format.test(str);

  let newStr = "";
  for (let i = 0; i < str.length; i++) {
    if (!format.test(str[i])) {
      newStr = newStr + str[i];
    }
  }

  return newStr;
}

function isPalindrome(str) {
  if (str.length === 0) {
    return true;
  } else {
    finalStr = isStrWithSpecialChar(str);
    if (finalStr.split(" ").length > 0) {
      arr = finalStr.split(" ");
      newStr = "";
      for (let i = 0; i < arr.length; i++) {
        newStr = newStr + arr[i];
      }
      lower_str = newStr.toLowerCase();
    } else {
      lower_str = finalStr.toLowerCase();
    }
    console.log(lower_str);

    flag = palindrome(lower_str);

    if (flag != 0) {
      return false;
    }
    return true;
  }
}

module.exports = isPalindrome;

<aside> 💡 My first attempt (not mentioned in this page) was correct if we went by the general premise of a palindrome to be ANY string -

</aside>

<aside> 💡 But this gives us good exercise to play around with strings, we learnt how to remove spaces, how to check for special characters, and how to remove special characters.

</aside>