UNPKG

d3

Version:

A small, free JavaScript library for manipulating documents based on data.

92 lines (80 loc) 2.13 kB
d3.layout.hierarchy = function() { var sort = d3_layout_hierarchySort, children = d3_layout_hierarchyChildren, value = d3_layout_hierarchyValue; // Recursively compute the node depth and value. // Also converts the data representation into a standard hierarchy structure. function recurse(data, depth, nodes) { var datas = children.call(hierarchy, data, depth), node = {depth: depth, data: data}; nodes.push(node); if (datas) { var i = -1, n = datas.length, c = node.children = [], v = 0, j = depth + 1; while (++i < n) { d = recurse(datas[i], j, nodes); d.parent = node; c.push(d); v += d.value; } if (sort) c.sort(sort); if (value) node.value = v; } else if (value) { node.value = value.call(hierarchy, data, depth); } return node; } // Recursively re-evaluates the node value. function revalue(node, depth) { var children = node.children, v = 0; if (children) { var i = -1, n = children.length, j = depth + 1; while (++i < n) v += revalue(children[i], j); } else if (value) { v = value.call(hierarchy, node.data, depth); } if (value) node.value = v; return v; } function hierarchy(d) { var nodes = []; recurse(d, 0, nodes); return nodes; } hierarchy.sort = function(x) { if (!arguments.length) return sort; sort = x; return hierarchy; }; hierarchy.children = function(x) { if (!arguments.length) return children; children = x; return hierarchy; }; hierarchy.value = function(x) { if (!arguments.length) return value; value = x; return hierarchy; }; // Re-evaluates the `value` property for the specified hierarchy. hierarchy.revalue = function(root) { revalue(root, 0); return root; }; return hierarchy; } function d3_layout_hierarchyChildren(d) { return d.children; } function d3_layout_hierarchyValue(d) { return d.value; } function d3_layout_hierarchySort(a, b) { return b.value - a.value; }