Reputation: 48
So I was doing this popular challenge "palindrome" and I was copying this solution from the "Frontend Masters" Javascript Series and I'm getting a different output. I want to know if there is something that changes or am I missing something. This is my first question on StackOverflow because this is just MindF***k.
What is going on?
'use strict'
function isPalindrome(str) {
if (str.length <= 1) return true;
var first = str[0];
var last = str[str.length - 1];
if (first === last) {
console.log(str.substring(1, str.length - 1))
isPalindrome(str.substring(1, str.length - 1));
}
return false;
}
console.log(isPalindrome("abcdcba")) // Return false on my machine
I try this on the RunJS app as well as the VScode terminal and also I run Node on the file.
KEEP RETURNING FALSE !!
Upvotes: 0
Views: 194
Reputation: 964
I fixed your code...
'use strict'
function isPalindrome(str) {
if (str.length <= 1) return true;
var first = str[0];
var last = str[str.length - 1];
if (first === last) {
console.log(str.substring(1, str.length - 1))
return isPalindrome(str.substring(1, str.length - 1));
}else return false;
}
console.log(isPalindrome("abcdcba")) //
I see recursive functions having two different parts:
if (str.length <= 1) return true
or if first !== last
.I think you you did it totally right going forward, but there was a minor details in the come back. You need to remember that ones you have your solution you need to return values through all the calls back to the initial one.
A recursive function is kind of split in two:
function recursive{
//forward processing
..
resultValue = recursive()
..
// backward processing if needed
return kindOfResultValue //resultValue or a transformation if needed
}
Note: Remember to check all conditional branches of your recursive function to return always a value after calling itself
Upvotes: 0
Reputation: 219026
The function will return true
if and only if the length of the input is <= 1
:
if (str.length <= 1) return true;
Which it isn't:
isPalindrome("abcdcba")
The only other return
statement in the function is:
return false;
It looks like you meant to return the recursive result:
return isPalindrome(str.substring(1, str.length - 1));
Otherwise the function never does anything with the result from calling itself recursively, and just defaults to returning false
on the last line.
Upvotes: 3