Question

In D3, the edge bundling example, we have this code

// Lazily construct the package hierarchy from class names.
function packageHierarchy(classes) {
  var map = {};

  function find(name, data) {
    var node = map[name], i;
    if (!node) {
      node = map[name] = data || {name: name, children: []};
      if (name.length) {
        node.parent = find(name.substring(0, i = name.lastIndexOf(".")));
        node.parent.children.push(node);
        node.key = name.substring(i + 1);
      }
    }
    return node;
  }

  classes.forEach(function(d) {
    find(d.name, d);
  });

  return map[""];
}

I can't figure out what return map[""]; means. Any ideas?

Was it helpful?

Solution

For each class it's given, it works recursively back through the parents, taking the class name up to the last ., adding each parent to the map as it goes, finally adding a parent with empty string for the name (there was no dot).

This parent is regarded as the root, and has a path of empty string, and this node is what is returned.

I'll try to explain better with an example;

Given a class with the full path Main.Sub.Class, the code will add the Main.Sub.Class node to the map with that path, and then try to find/create a node for Main.Sub, and add itself as a child to this parent node.

If it has to create a new node for Main.Sub, it will try to find the parent for this class too, (Main), and add Main.Sub as a child to Main. It then continues up again, but since there is no . in the path, the parent path is "" (empty string).

Since all classes will eventually end up adding themselves as a child to the empty string node, this node can be considered the root node, and so is the node to be returned.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top