Friday, June 11, 2021

Javascript Practice 76: JS Hero - Recursion

 
Question: 

Write a function reverse that reverses the order of the characters in a string. The function should be recursive.

Example: reverse('live') should return 'evil'.




Answer: 

function reverse (str) {

if (str < 1) {

return ''; 

} else {

return reverse(str.substr(1)) + str.charAt(0);

}
};





> we first declare a function 'reverse'
> it has one parameter 'str' 
> our goal is to take a string and reverse it as the name suggests
> we shall do the reversing using recursion 
> recursion is a function or a method that calls itself several times till it meets the base case 
> because it is a recursion we shall be needing a base case
> this base case will let us know when to stop running the recursion over and over 
> in the process of 'reverse' function we shall be chopping off the first letter / character over and over
> which will eventually lead to the length of the string be: ' less than 1 ' 
> so when our string length is ' less than 1 ' our string is empty and we want to return it
> and so we return an empty string: '' ; as we want the end result to be a 'string'
> we do that like this: if (str < 1) return ''
> now we start to think about the else statement 
> we want our string to be in reverse 
> so we want to return each of the letters / characters in reverse order
> so the first thing we need to do is to get the first character of our string
> we shall use the charAt(0) method to get our first character / letter
> after we get the first letter / character of the string then we want to run the 'reverse' function on all the letters / characters after the first letter / character
> so if our string was: 'hello' 
> then by using charAt(0) we would get the letter / character 'h' 
> we then would want to use the 'reverse' function on 'ello'  and simultaneously append all the first characters
> and consequently get rid of one letter each time 
> so the way to get rid of the first letter and still run the function is to use the substr() method
> like this: reverse(str.substr(1)) + str.charAt(0) 
> this will keep repeating itself till our base case is met which is an empty string
> for eg. if our string is: 'hello'  we would want 'olleh'
> step 01 = ello + h
> step 02 = llo + e + h 
> step 03 = lo + l + e + h
> step 04 = o + l + l + e + h
> thus when the 'if' condition is true then we shall be returned with a reversed string







No comments:

Post a Comment