Billipede.net

"You just won't believe how vastly, hugely, mind-bogglingly big it is."

filed under:

2015-01-17 Trees are Just Lists

Trees are just lists of lists. That may sounds obvious to you if you hang out on comp.lang.scheme, know what a zclosure is, or really if you've ever used the word "tree" to describe something that isn't made of wood. Still, it's a significant fact, and it would be nice if the developers or specifiers of standard libraries in dynamic, scripty languages would remember it. Specifically, I'm kvetching about the fact that Javascript doesn't have, so far as I can tell, a built-in array "map" function that can recursively walk sub-arrays. I can see that there might be situations where one might want to map only the top level of an Array of Arrays, but can't we just use forEach or even just plain old for?
In any case, in the hopes that others on the internet may need a recursive Javascript map in a pinch and don't want to spend 5 minutes writing one themselves, I give you this:
function mapTree(tree, func) { function mapTreeHelper(x) { if (Array.isArray(x)) { return x.map(mapTreeHelper); } else { return func(x); } } return tree.map(mapTreeHelper); }
Now you can get back to whatever it was that you were actually coding up. You're welcome.