I will share my approach to recursion.
It works for me when it comes to simple cases.
Example
Task: make recursive function which returns product of
2 positive numbers a and b
Hint: for the sake of learning use basic math rule:
a * b >>>> it is the same as : a + a + ...+a b times
Thought process:
recursion consists of 2 main things:
base case - it’s usually MOST SIMPLE case of your problem,
for us it will be case when b===1 (not 0, we are doing this stuff for positive numbers for now)
without BASE CASE our recursion will be the same mess as infinite loop:
it will never end
recursive step is the second thing we need
and here is often the most confusion begins
How I am trying to think:
I grab some case of my problem.
Not the base case , but something what can be easily analyzed
For this example I will grab case when b===4.
Lets say a === 2 (we can use any a in our case
not really that big of a deal for us in our studies now)
By the way, my fucntion is called
recursivePositivesProduct
recursivePositivesProduct(2,4) must return 8
also I can say
recursivePositivesProduct(2,b) must return 8 when b ===4
And now grab little more simple case, adjacent to our case above,
for us it will be (b - 1)=== 3
recursivePositivesProduct(2,3) must return 6
also I can say
recursivePositivesProduct(2,b - 1) must return 6 when b ===4
So, KEY THOUGHT:
Recursive step is the difference between adjacent cases, for us it is the difference
between
recursivePositivesProduct(2,b) =>>> 8
and
recursivePositivesProduct(2,b - 1) =>>>6
so for our little task this difference easy to grasp:
for a === 2 =>>> difference is 2
in general difference is equal to the value of a
And now when I know the difference I can say:
recursivePositivesProduct(a,b)
it is the same as
recursivePositivesProduct(a,b - 1) + a
And now we basically need to add base case and recursive step together
const recursivePositivesProduct = (a,b) => {
//base case
if (b === 1) {
return a; ///a * 1 === a obviously
}
//recursive step
else {return recursivePositivesProduct(a, b - 1) + a}
}
console.log(recursivePositivesProduct(7, 1))//7
console.log(recursivePositivesProduct(4,5))//20
console.log(recursivePositivesProduct(9,5))//45