2

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?

VividD
  • 10,456
  • 6
  • 64
  • 111
Orkun
  • 6,998
  • 8
  • 56
  • 103

1 Answers1

2

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.

Pudge601
  • 2,048
  • 1
  • 12
  • 11
  • bonus question:) is the 'children' a reserved keyword or can i replace it with anything? – Orkun Jun 03 '14 at 14:39
  • Erm.. from what I can see of how that's being used, I think it has to be called `'children'` because the root gets passed to `d3.layout.cluster()` which I think expects to have the `children` property on each of the nodes. Not entirely sure though, I've never looked at d3 before.. – Pudge601 Jun 03 '14 at 14:44
  • 1
    However, looking further on, I've seen this in the documentation; https://github.com/mbostock/d3/wiki/Cluster-Layout#children. I think that should allow you to override the function for retrieving the children from a given node, that would have to be called on the `cluster` variable. So changing the definition of the `cluster` variable to something like this; http://pastebin.com/rC6ry0nC would allow you to rename the `children` property to `offspring`. – Pudge601 Jun 03 '14 at 14:47