Recursion - Basic Explanation
Hi folks ,
Today I thought to write about Recursion, a powerful functional programming concept
First, let's see the etymology of this term Recursion, It comes from the Latin word "recurrere" which means RUN BACK from this we can get some idea that we are going to walk/run again on the same track again and again
We can also consider Recursion as a thinking style like breaking down a complex thing into smaller parts and composing them together to arrive at the final solution
When I saw the recursion for the first time, I was so surprised to see the function calls itself, this is one of the unique qualities of recursion
Ok now , let's see an example to know what is recursion? ,using a simple JavaScript code
?const drivers = [{ id: 1, name: "Adam", exp: "5years" }, { id: 2, name: "Chola", exp: "2years" }, { id: 3, name: "Paari", exp: "3years" }, { id: 4, name: "Guru", exp: "5years" }, { id: 5, name: "Jeron", exp: "4years" },
? ? //map method
? ? const listOfDrivers = drivers.map(driver => driver.name)
? ? console.log(listOfDrivers, "listOfDrivers")
? ? // Recursive method
? ? const listOfRecurDrivers:any = []
? ? const filterDrivers = (drivers: any) => {
? ? ? ?// base case if (drivers?.length > 0)
{
// Recursive Case
? ? ? ? ? ? const {name} = drivers.shift()
? ? ? ? ? ? listOfRecurDrivers.push(name)
// function has been called in itself
? ? ? ? ? ? filterDrivers(drivers)
? ? ? ? }
? ? ? ? else{
? ? ? ? console.log(listOfRecurDrivers,"listOfRecurDrivers")
? ? ? ? }
? ? }
? ? filterDrivers(drivers)
In the above example we have used the recursion to its simplest form but it is capable of doing complex operations , likewise we also can infer that Recursion is very similar to Iteration
领英推荐
I have written a code to pull the names of the drivers from an array of objects and make a new array of names using both map method and recursive method to give some basic clarity on how recursion works
Recursion has two main parts
Usually we use alot of iterations in our code , when things get complex we can try recursion to make it more expressive and powerful
The above example is a very simple example like I said before, to give the taste on how recursion looks ? I have used this example , same thing can be written in various ways and we can play around with this technique
Though Recursion is a powerful technique it may also bring a slowness to the performance , I think that has to be taken into consideration when we use recursion in our code
I hope this gave you some idea about Recursion which you can use it in your code to solve any problems which you are encountering
Thanks for your time,
-VMKrishna