Anurag Sinha
TechnCode

TechnCode

Palindrome Implementation - via JavaScript

Palindrome Implementation - via JavaScript

Anurag Sinha's photo
Anurag Sinha
·Nov 25, 2021·

2 min read

Introduction

  • This is the 2nd post in the DS and Algo practice series.
  • Here we would have a look at what is a palindrome and implement it via JavaScript.

What is a Palindrome ?

  • Well, palindrome is a string which when reversed generates the same string.
  • For ex: "abba", "civic". If we reverse either "abba" or "civic", we would get back the same string.

Implementations

1) We would reverse the input string and then compare the reversed string with the input one.

We ignore the spaces and case sensitivity, while looking for palindromes.

Ex: "taco cat" when reversed would ideally generate the same string when reversed. Here we need to ignore the white space while doing comparison. Same goes for case sensitivity.

//Palindrome
function isPalindrome(str) {
  if (!str) {
    return "Invalid Input";
  }
  let reversedStr = str
    .replace(/ +/g, "")
    .split("")
    .reduce((rev, item) => item + rev, "");

  return str.replace(/ +/g, "").toLowerCase() === reversedStr.toLowerCase();
}

console.log(isPalindrome("abba"));
console.log(isPalindrome("abcd"));
console.log(isPalindrome("racecar"));
console.log(isPalindrome("civic"));
console.log(isPalindrome("taco cat"));
console.log(isPalindrome("Aibohphobia"));
console.log(isPalindrome(null));
console.log(isPalindrome(""));
console.log(isPalindrome("A Santa Lived As a Devil At NASA"));

image.png

2) Second implementation makes using of Array.prototype.every() method of JavaScript, would be slightly lengthier option than the first one, because every() method will try to traverse every single element of the incoming array.

But anyways, its an alternate implementation and it's always better to know multiple solutions to a problem.

//Alternate implementation using every() method
function isPalindromeUsingEvery(str) {
  if (!str) {
    return "Invalid Input";
  }
  let trimmedStr = str.replace(/ +/g, "");
  return trimmedStr.split("").every((item, index) => {
    return (
      item.toLowerCase() ===
      trimmedStr[trimmedStr.length - index - 1].toLowerCase()
    );
  });
}

console.log(isPalindromeUsingEvery("abba"));
console.log(isPalindromeUsingEvery("abcd"));
console.log(isPalindromeUsingEvery("racecar"));
console.log(isPalindromeUsingEvery("civic"));
console.log(isPalindromeUsingEvery("taco cat"));
console.log(isPalindromeUsingEvery("Aibohphobia"));
console.log(isPalindromeUsingEvery(null));
console.log(isPalindromeUsingEvery(""));
console.log(isPalindromeUsingEvery("A Santa Lived As a Devil At NASA"));

image.png

Full code is present at - github.com/anurag1302/dsalgo-javascript/blo..

 
Share this