Would someone review this code, and confirm that it is indeed recursive? I'm learning computer science and going through different types of algorithms. Right now, I'm focusing on recursion want to ensure that this 'recursive palindrome' method is truly recursive. I've passed six different strings as a test, three that were palindromes and three that were not. The method worked as expected, but again; I'm really looking for a cross-check to ensure this is recursive.
From my understanding, when writing recursive algorithms, the base case should take care of the end of the recursive process. Or, in other words, it should solve the very last sub-problem of the algorithm, after all the recursion has taken place. Please correct me if I am wrong in that thinking.
My observation here is that at some point, the string will end up with 1 character no matter what. Again, the base case should take care of that, but it doesn't. That is why I added the if (str.slice(1, -1).length === 1)
check inside of if (firstChar === lastChar)
. If the method breaks the word down and it is one character and a palindrome, then it will return 'String is a palindrome.' This can be verified when passing 'racecar' as a parameter of the method.
function obtainFirstCharacterOfString(str) {
const firstChar = str.slice(0, 1);
return firstChar;
}
function obtainLastCharacterOfString(str) {
const lastChar = str.slice(-1);
return lastChar;
}
function recursivePalindrome(str) {
// Base case
if (str.length === 0 || str.length === 1) {
return 'String is not a palindrome';
}
const firstChar = obtainFirstCharacterOfString(str);
const lastChar = obtainLastCharacterOfString(str);
if (firstChar === lastChar) {
if (str.slice(1, -1).length === 1) {
return 'String is a palindrome';
} else {
return recursivePalindrome(str.slice(1, -1));
}
} else {
return 'String is not a palindrome';
}
}