Using Recursion – Sometimes an Elegant Solution

Recursion is a technique where a function gets part of the way through a solution, then calls itself to continue the solution process.

Certain types of problems such as iterating through a directory and finding all the nested folders and documents can be conveniently solved using a recursion.

A caveat however, is that successive recursive calls push the function’s scope onto a stack.  If there is a limit to that stack that is reached by your processing, your program will fail with the classic “Stack Overflow” type error.

So if you choose to implement a recursive algorithm it would be wise to build a test that verifies the algorithm works in the target environments and do a little research to find out how deep nesting of function calls may be in your environments.  I say environments plural because there are many versions of web browsers for example that one’s web app may run on.

Recently, I stumbled upon a programming challenge that intrigued me.  As I started to sketch out a process to solve the problem, it dawned on me that the solution would be quite short using a recursive algorithm.  I’ve changed the wording of the challenge a little in the hopes that others who find and take on the original challenge, will not readily find this solution.

I’ve put both the challenge and my JavaScript solution into a web page where you can open, re-run and even harmlessly modify the code if you like.

To see the challenge and JavaScript code that solves it, follow this link:

 

https://bseaver.jsbin.com/gahuqeh/edit?js,output

Thanks for looking!