Monday, July 27, 2020

Palindrome Checker

From: https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/javascript-algorithms-and-data-structures-projects/palindrome-checker

JavaScript Algorithms and Data Structures Projects: Palindrome Checker
Return true if the given string is a palindrome. Otherwise, return false.

A palindrome is a word or sentence that's spelled the same way both forward and backward, ignoring punctuation, case, and spacing.

Note
You'll need to remove all non-alphanumeric characters (punctuation, spaces and symbols) and turn everything into the same case (lower or upper case) in order to check for palindromes.

We'll pass strings with varying formats, such as "racecar", "RaceCar", and "race CAR" among others.

We'll also pass strings with special symbols, such as "2A3*3a2", "2A3 3a2", and "2_A3*3#A2".


const removeAllNonNumeric = str => str.replace(/[\W_]/g, '');

function palindrome(str) {
  const clean = removeAllNonNumeric(str).toLowerCase();
  const len = clean.length;
  const mid = len / 2;

  for (let start = 0, end = len - 1; start < mid; ++start, --end) {
      if (clean[start] !== clean[end]) {
          return false;
      }
  }
  return true;
}

[
    "eye",
    "eye",
    "_eye",
    "race car",
    "not a palindrome",
    "A man, a plan, a canal. Panama",
    "never odd or even",
    "nope",
    "almostomla",
    "My age is 0, 0 si ega ym.",
    "1 eye for of 1 eye.",
    "0_0 (: /-\\ :) 0-0",
    "five|\\_/|four",
].forEach(arg => console.log(arg, ':', palindrome(arg)));



Output:
eye : true
eye : true
_eye : true
race car : true
not a palindrome : false
A man, a plan, a canal. Panama : true
never odd or even : true
nope : false
almostomla : false
My age is 0, 0 si ega ym. : true
1 eye for of 1 eye. : false
0_0 (: /-\ :) 0-0 : true
five|\_/|four : false

No comments:

Post a Comment