Last active
February 9, 2024 13:51
-
-
Save jmcook1186/5424024163b62aaaa47c5493b8a814b3 to your computer and use it in GitHub Desktop.
IF: draft aggregation function
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** 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