block by timelyportfolio 612c434485cfccddfa15049bbeb099c9

generalized aggregate for hierarchy

Full Screen

Built with blockbuilder.org

index.html

<!DOCTYPE html>
<head>
  <meta charset="utf-8">
  <script src="https://d3js.org/d3.v4.min.js"></script>
  <style>
    body { margin:0;position:fixed;top:0;right:0;bottom:0;left:0; }
  </style>
</head>

<body>
  <pre id="results"></pre>
  <script>
 		var data = {
      name: 'root',
      children: [
        {
          name: 'A',
          children: [
          	{name: 'A1', x:1},
          	{name: 'A2', x:10}
        	]
        },
        {
          name: 'B',
          children: [
          	{name: 'B1', x:50},
          	{name: 'B2', x:-3},
            {name: 'B3', x:100}
        	]
        },
      ]
    }
    
    var root = d3.hierarchy(data);

    function aggregate(f, valuef, name) {
      return this.eachAfter(function(node) {
        var children = node.children,
          values;
        if(children && children.length) {
          values = children.map(function(d){return d[name]});
        } else {
          values = [valuef(node)];
        }
        var agg = f(values);

        node[name] = agg;
      });
    }
    
    console.log(
      aggregate.call(root,d3.max,function(d){return d.data.x},'max')
    );
    
    var results = [];
    root.eachBefore(function(d){results.push(d.data.name + ' max:' + d.max)});
    d3.select('#results').text(
    	results.join('\n')
    );
  </script>
</body>