I was chuffed you can echo scope through recursions in JavaScript.
Thought I'd share. I have only seen this in more nerdier languages but it solved a gnarly parse problem.
In this case I needed to build tree permutations as arrays. [a,e,1],[a,f,1],[a,e,2],[a,f,2] etc.
Seemed like a good excuse to try some recursion. But the function needed to be low lag and self contained. head scratcher!
allUniqueNames = [["A","B","C","D"],["E","F","G"], ["1","2"]];
function recurseDimensionalTree(arr,tree){ if(tree == undefined){ tree=["trunk"]; } var newBranch = arr.shift(); var mould = []; for(var f in tree){ for(var t in newBranch){ mould.push(tree[f]+"||"+newBranch[t]); } } tree = mould; if(arr.length>0){ //The return keyword here runs the next iteration before closing return recurseDimensionalTree(arr,tree); }else{ for(var i in tree){ tree[i] = tree[i].split("trunk||").join("").split("||"); } } //The scope chain eventually cascades back to iteration 1 and runs the tail return return tree; } console.log(recurseDimensionalTree(allUniqueNames));
/* returns: [A,E,1],[A,E,2],[A,F,1],[A,F,2],[A,G,1],[A,G,2],[B,E,1],[B,E,2],[B,F,1],[B,F,2],[B,G,1],[B,G,2],[C,E,1],[C,E,2],[C,F,1],[C,F,2],[C,G,1],[C,G,2],[D,E,1],[D,E,2],[D,F,1],[D,F,2],[D,G,1],[D,G,2] */
Without the recursion tail, tree would become undefined and the dream collapses, etc.
This runs in 7-14 ms in chrome. Although Chrome, I would think is optimizing it classically. Mileage in other browsers may vary.
I was surprised this worked at all. The js engine of each browser needs to recognize the tail setup for this to work otherwise the first return would return to the caller. It would probably be a memory danger on very large work, but I know my arrays are going to be limited.
Not of direct use to me, but I enjoy reading how you approach and solve it and I learn - thanks
np.
a quick test shows it works in all versions of actionscript as well. This might not run in legacy browsers, depending on how broken the ecma compliance is.
It's a nice alternative to loops where an operation like this would inevitably end up with a bunch of nested loops and then endanger timing out the page when a nested loop takes to long to work. As well it potentially encapsulates recursion if it were made a member of a prototype class.
Ran into a similar situation years back. It was building an admin interface for managing inventory. Don't remember what we ended up doing on the script side to handle the various combos, just remember it requiring a lot of head scratching and drawings when trying to envision some of the more complex inventory scenarios.