-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathRecursion-1.js
44 lines (38 loc) · 1.13 KB
/
Recursion-1.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
Challenge: is a string a palindrome?
// 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);
Program.assertEqual(isPalindrome("lrotorl"), true);
Program.assertEqual(isPalindrome("motr"), false);