Created
April 9, 2017 13:33
-
-
Save zeraf29/00ab4c1fbcf2ed483b42f9e885f083c5 to your computer and use it in GitHub Desktop.
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
// Returns the first character of the string str | |
var firstCharacter = function(str) { | |
return str.slice(0, 1); | |
}; | |
// Returns the last character of a string str | |
var lastCharacter = function(str) { | |
return str.slice(-1); | |
}; | |
// Returns the string that results from removing the first | |
// and last characters from str | |
var middleCharacters = function(str) { | |
return str.slice(1, -1); | |
}; | |
var isPalindrome = function(str) { | |
// base case #1 | |
if(str.length<=1){ | |
return true; | |
} | |
// base case #2 | |
if(firstCharacter(str)!==lastCharacter(str)){ | |
return false; | |
} | |
// recursive case | |
return isPalindrome(middleCharacters(str)); | |
}; | |
var checkPalindrome = function(str) { | |
println("Is this word a palindrome? " + str); | |
println(isPalindrome(str)); | |
}; | |
checkPalindrome("a"); | |
Program.assertEqual(isPalindrome("a"), true); | |
checkPalindrome("motor"); | |
Program.assertEqual(isPalindrome("motor"), false); | |
checkPalindrome("rotor"); | |
Program.assertEqual(isPalindrome("rotor"), true); | |
checkPalindrome("101101"); | |
Program.assertEqual(isPalindrome("101101"), true); | |
checkPalindrome("Today is si yadoT"); | |
Program.assertEqual(isPalindrome("Today is si yadoT"), true); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment