Skip to content

Instantly share code, notes, and snippets.

@jmcook1186
Last active February 9, 2024 13:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jmcook1186/5424024163b62aaaa47c5493b8a814b3 to your computer and use it in GitHub Desktop.
Save jmcook1186/5424024163b62aaaa47c5493b8a814b3 to your computer and use it in GitHub Desktop.
IF: draft aggregation function
/** This function does a depth-first, post-order traversal of the tree and aggregates the named metrics from each child into the parent node all the way up to the root*/
const tree = {
name: "Root",
carbon: 0,
energy: 0,
children: [{
name: "A",
energy: 40,
carbon: 10,
children: [{
name: "C",
carbon: 35,
children: [
{
name: "E",
carbon: 50,
energy: 10,
children: []
}, {
name: "F",
energy: 20,
carbon: 33,
children: []
}]
},
{
name: "D",
energy: 30,
carbon: 35,
children: []
}
]
},
{
name: "B",
energy: 40,
carbon: 10,
children: []
}
]
};
let context = {
metrics: ['carbon', 'energy']
}
function hasChildren(tree) {
if (tree['children'].length > 0) {
return true
}
}
function getChildren(tree) {
return tree['children']
}
function aggregation(tree, context) {
// check if root has children
if (hasChildren(tree)) {
// iterate through child nodes
getChildren(tree).forEach(node => {
// if the child has children, start recursive call to aggregate()
if (hasChildren(node)) {
aggregation(node, context)
}
context['metrics'].forEach(metric => {
if (!(tree[`aggregated-${metric}`])) {
if (node[`aggregated-${metric}`]) {
tree[`aggregated-${metric}`] = tree[`${metric}`] + node[`aggregated-${metric}`]
} else {
tree[`aggregated-${metric}`] = tree[`${metric}`] + node[`${metric}`]
}
}
else {
if (node[`aggregated-${metric}`]) {
tree[`aggregated-${metric}`] += node[`aggregated-${metric}`]
} else {
tree[`aggregated-${metric}`] += node[`${metric}`];
}
}
})
})
}
return tree
}
const newTree = aggregation(tree, context)
console.log(newTree)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment