Skip to content

Instantly share code, notes, and snippets.

@rjschie
Created September 24, 2015 23:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rjschie/b9fb18398db181c72dee to your computer and use it in GitHub Desktop.
Save rjschie/b9fb18398db181c72dee to your computer and use it in GitHub Desktop.
Heard a problem set the other day to make a function detecting if a string is a palindrome. Wanted to give it a shot.
'use strict';
function reverseString(input) {
var result = "";
for( var i = (input.length-1); i >= 0; i-- ) {
result = result + input[i];
}
return result;
}
function collectToIndex(input, index) {
var result = "";
for( var i = 0; i < index; i++ ) {
result += input[i];
}
return result;
}
function isPalindrome(input) {
var rightSide, leftSide, collectionIndex;
if( (input.length % 2) == 0 ) { // If odd, set our index up one to grab proper character
collectionIndex = (input.length / 2) + 1;
} else {
collectionIndex = (input.length / 2);
}
leftSide = collectToIndex(input, collectionIndex);
rightSide = collectToIndex(reverseString(input), collectionIndex);
if(leftSide == rightSide) {
return true;
} else {
return false;
}
}
console.log( isPalindrome('racecar') ); // -> true
console.log( isPalindrome('racercars') ); // -> false
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment