Palindrome

code
Photo by Markus Spiske / Unsplash

Determine whether the input string is a palindrome or not

const isPalindrome = (str) => {
  if (
    str.length === 0 ||
    str === undefined ||
    str === null ||
    typeof str !== 'string'
  )
    return false;

  let newCleanedString = stringClean(str);
  let leftPointer = 0;
  let rightPointer = str.length - 1;
  while (leftPointer < rightPointer) {
    if (newCleanedString[leftPointer] === newCleanedString[rightPointer]) {
      leftPointer++;
      rightPointer--;
    } else {
      return false;
    }
  }
  return true;
};

const stringClean = (str) => {
  if (
    str.length === 0 ||
    str === undefined ||
    str === null ||
    typeof str !== 'string'
  )
    return false;
  return str.replace(/[\W_ ]/g, '').toLowerCase();
};


const { isPalindrome, stringClean } = require('../palindrome.js');

const isPalindromeCases = [
  ['', false],
  ['aB-b-Ba', true],
  ['a bCde', false],
  ['100 01', true],
  ['111 111 1 1', true],
  ['123450', false],
  ['MadamImAdam', true],
  ['l O L', true],
  ['O_O (:/-:) O_O', true],
  ['!a_b. A_$?', true],
  [777, false],
  [1111111, false],
];

describe('isPalindrome Test', () => {
  test.each(isPalindromeCases)(
    'given %p as argument returns %p',
    (firstArg, expectedResult) => {
      let cleanedString = stringClean(firstArg);
      let actual = isPalindrome(cleanedString);
      expect(actual).toBe(expectedResult);
    }
  );
  it('isPalindrome() function should exist', () => {
    expect(typeof isPalindrome).toBe('function');
  });
  it('isPalindrome() function expects exactly 1 argument', () => {
    expect(isPalindrome.length).toBe(1);
  });
});