JS Algorithm – Palindrome

Machu Picchu, Peru by https://unsplash.com/@willianjusten

Given a string, return true if the string is a palindrome or false if it is not. Palindromes are strings that form the same word if it is reversed.

Do include spaces and punctuation in determining if the string is a palindrome.

Examples:

palindrome(“abba”) === true

palindrome(“abcdefg”) === false

1 Solution:

function palindrome(str) {
  // First reverse the string
  const reversed = str.split('').reverse().join('');

  // Compare the original string with the reversed string
  if (str === reversed) {
    return true;
  } else {
    return false;
  }
}

palindrome('abba');

Result:

Also we can do something like this for comparing the strings:

return str === reversed;

2 Solution:

This solution is not the ideal solution because create a lot of comparations, but is another way to resolve this algorithm

function palindrome(str) {
  // The every checks if all elements in an array pass
  // a test (provided as a function)
  return str.split('').every((character, index) => {
    // Comparing actual character with the last character of the array
    return character === str[str.length - index - 1];
  });
}

palindrome('abcdefg');

Result:

By Cristina Rojas.