Created
September 24, 2015 23:48
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'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