Skip to content

Instantly share code, notes, and snippets.

@zackproser
Created December 18, 2016 01:40
Show Gist options
  • Save zackproser/f6115513ca03049278af6e2ada3dc180 to your computer and use it in GitHub Desktop.
Save zackproser/f6115513ca03049278af6e2ada3dc180 to your computer and use it in GitHub Desktop.
isPalindrome Function in Javascript
/**
* Checks whether a supplied string is a palindrome,
* meaning it is spelled the same forwards and backwards
*
* @param {String} - The string to check
* @return {Boolean} - True, if the string is a palindrome. False, if it is not.
*/
function isPalindrome(stringToCheck) {
/**
* Reverses a string and returns it
*
* @param {String} - The string to reverse
* @return {String} - The reverse of the supplied string
*/
function reverseString(stringToReverse) {
//Split string characters into an array and mark its start and end indexes
var
chars = stringToReverse.split(''),
startIndex = 0,
endIndex = chars.length - 1
;
//Step from the beginning and end of the array
//toward the middle, swapping the characters at the start
//and end indexes
while (startIndex < endIndex) {
var left = chars[startIndex];
chars[startIndex] = chars[endIndex];
chars[endIndex] = left;
startIndex++;
endIndex--;
}
return chars.join('');
}
//If a word is the same forwards and backwards, it is a palindrome
return (stringToCheck === reverseString(stringToCheck));
}
var words = ["wakka", "radar", "civic", "tree"];
words.forEach((word) => {
console.log(isPalindrome(word));
});
//wakka -> false
//radar -> true
//civic -> true
//tree -> false
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment