I've tried to write a recursive palindrom however, eventhough I reach at the end the true branch at the last iteration the return value is still undefined.
So if you type in the console my function with a palindrom. rekurzivSzigoruPalindrom("radar");
It will iterate through it perfectly but the return value, will be undefined. Could you please point out the error in my code below ? Thanks
function rekurzivSzigoruPalindrom(str, strLength = str.length) {
// debug eleje
console.log(strLength);
if (strLength > 1) {
console.log(str[str.length - strLength] + " " +str[strLength-1] );
}
if(strLength == 1){
console.log(str[str.length-1]+ " " +str[strLength-1]);
}
//debug vége
if(typeof str == "string" || typeof str == "number"){
if(typeof str == "number"){
str = str.toString();
}
if(strLength > 1){
if(str[str.length - strLength] == str[strLength-1]){
//console.log(strLength);
strLength--;
rekurzivSzigoruPalindrom(str,strLength);
}
}
else if(strLength == 1){
if(str[str.length-1] == str[strLength-1]){
console.log(strLength+"true");
return true;
}
else{
console.log(strLength+"false");
return false;
}
}
}
else {
return false;
}
}
you have to return the result of your recursive call.
function rekurzivSzigoruPalindrom(str, strLength = str.length) {
// debug eleje
console.log(strLength);
if (strLength > 1) {
console.log(str[str.length - strLength] + " " +str[strLength-1] );
}
if(strLength == 1){
console.log(str[str.length-1]+ " " +str[strLength-1]);
}
//debug vége
if(typeof str == "string" || typeof str == "number"){
if(typeof str == "number"){
str = str.toString();
}
if(strLength > 1){
if(str[str.length - strLength] == str[strLength-1]){
//console.log(strLength);
strLength--;
return rekurzivSzigoruPalindrom(str,strLength);
}
}
else if(strLength == 1){
if(str[str.length-1] == str[strLength-1]){
console.log(strLength+"true");
return true;
}
else{
console.log(strLength+"false");
return false;
}
}
}
else {
return false;
}
}