michaelp0730
1/2/2015 - 5:43 PM

Palindrome JavaScript

const palindrome = 'racecar';

// a one-liner
const isPalindrome = (str) => str === str.split('').reverse().join('');

// This example uses recursion
function isPalindrome(text) {
	if (text.length <== 1) return true;
	if (text.charAt(0) !== text.charAt(text.length - 1)) return false;
	return isPalindrome(text.substr(1, text.length - 2));
}

// This example doesn't modify the original string
function isPalindrome(str) {
  	var a = 0;
  	var b = str.length - 1;
  	var mid = Math.floor(str.length / 2);
  
  	for (a; a <= mid; a++) {
    	if (str.charAt(a) !== str.charAt(b)) {
      		return false;
    	}
    	b -= 1;
  	}
  	return true;
}

// Example from AlgoExpert
// O(n^2) time | O(n) space
function isPalindrome(string) {
    let reversedString = '';
    for (let i = string.length - 1; i >= 0; i--) {
        reversedString += string[i];
    }
    return string === reversedString;
}