Sunday, August 23, 2015

Recursive Functions in real life

Recursive functions are one of those things that seem to only occur in hypothetical situations. Well this week I wrote a real life one for a good reason. The goal was to create a dynamic HTML tree structure with an unknown number of children, grandchildren, great-grandchildren, etc. Each parent would be a LI inside of a UL. All children would be contained in their own UL, with child LI's, and keep on looping...  The goal was to look like this: https://jsfiddle.net/jhfrench/GpdgF/ but build the HTML dynamically. Here is how I solved it in Asp.NET C#.

I get a list of all of the Ids that will be used, so if the user selects a hierarchy that is Id 1, Id 2, Id 3, my list will contain [1,2,3]. I pass this list into my LoopParams function, and use an iterator to figure out which Id I am going for. I can then use iterator + 1, to get at the next Id in the series. This allows me to continue querying for the next available Ids, and if they exist, add a new UL and child LI's. If they don't exist, I just add the one LI and move on to the next parent.


The end result was something like this, which changes dynamically as each "Function Type is selected:


SUCCESS!

No comments:

Post a Comment