Skip to content
Advertisement

Recursion with map function in javascript

I have a map like this, which represents a graph:

JavaScript

And I have this class, which creates a rooted tree:

JavaScript

My goal is: given a root, I want to convert that graph to a rooted tree. For the example above, using 1 as root, I want the following return:

JavaScript

Here’s my code:

JavaScript

I’m receiving an empty array from the toRT function. I guess I probably messed up with the variables, but I don’t know how to fix it.

Advertisement

Answer

@Ajax’s answer is fine, but you mentioned that you had a Map, and wanted that Map instance to be an argument to toRT (good!).

So then the code is:

JavaScript

Explanation

From your question it is clear you are comfortable with Map and spread syntax, so let’s focus on this expression:

JavaScript

The optional chaining operator, i.e. ?., will ensure that .map() is only called when map.get(data) is defined. Otherwise undefined will be used instead of the .map() result.

.map() will iterate the child values found in the Map entry for data and translate each of them by a call to toRT(child, map). The latter will return a RootedTree instance, so the .map() call will return an array of such instances, and they will serve as descendants for the node we are constructing for data.

Finally, the Nullish coalescing operator, i.e. ??, will translate the undefined value (that came from map.get()) to an empty array. This way the spread operator will work correctly also in that case.

So the deeper nodes are created first, providing the descendants arguments for the outer new RootedTree calls. The root node is the last one created.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement