A Recursion Function in Real World Problem

A recursion function is a function that calls itself. Classic example is a Fibonacci series generator, which can be implemented by following:

That might be sufficient to demonstrate how recursion works, but sometimes we wonder where to apply it in real world (regardless of performance issues) like in web development, not just a pedagogic example.

I just encountered one scenario in work that can apply recursion. Say you have a web page which contains navigation like below. How do we get the index of each list item?

You might think that’s easy. Just make an array of all list items and get indexes:

How about we want to know the index of list user clicks on? Surely we can query the content of the clicked list and use the content as argument passed into previous `getIndx` function, but sometimes the world is not perfect, and we don’t have the privilege to query the inner content of a list element so easily, like when we encounter the following list:

Wanna pass the whole link content, including the `a` tag, as argument to `getIndx` function, to test if it matches the content of any list element in our list array? Well, maybe not to me, because it’s quite a long string, not to mention it might get more complicated if what’s in your list element increases.

Here recursion comes to rescue. Instead of getting the index from an array of list elements, we can count how many siblings the clicked list element has, which is equal to it’s index.

This is even more useful when you encounter a very “unusual” list, like the one below, and you cannot make it cleaner (no matter how and why).

You can filter out the siblings which is a paragraph and just count list elements.

P.s. A while version of this recursion function:

The difference between iteration and recursion has very important implication regarding to memory management.