Last active
August 29, 2018 14:56
-
-
Save JaosnHsieh/7d916cb242ecd51088e0cf87d9596a6b to your computer and use it in GitHub Desktop.
A silly way to get values from leaf bottom up. https://codepen.io/jasonhsieh/pen/PdGxGR?editors=0012
This file contains hidden or 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
| var tree = [ | |
| { | |
| label: "a", | |
| children: [ | |
| { | |
| label: "a-2-1", | |
| children: [ | |
| { | |
| label: "a-3-1", | |
| value: 3 | |
| } | |
| ] | |
| }, | |
| { | |
| label: "a-2-2", | |
| children: [ | |
| { | |
| label: "a-3-2", | |
| value: 2 | |
| }, | |
| { | |
| label: "a-3-3", | |
| value: 3 | |
| } | |
| ] | |
| } | |
| ] | |
| }, | |
| { | |
| label: "b", | |
| children: [ | |
| { | |
| label: "b-2-1", | |
| children: [ | |
| { | |
| label: "b-3-1", | |
| value: 5 | |
| } | |
| ] | |
| }, | |
| { | |
| label: "b-2-2", | |
| children: [ | |
| { | |
| label: "b-3-2", | |
| value: 2 | |
| }, | |
| { | |
| label: "b-3-3", | |
| value: 4 | |
| } | |
| ] | |
| } | |
| ] | |
| } | |
| ]; | |
| const sum = (node, ...sums) => { | |
| if (node.children) { | |
| const tempSums = []; | |
| for (let n of node.children) { | |
| n.sum = { | |
| count: 0 | |
| }; | |
| sum(n, ...sums, n.sum); | |
| } | |
| } else { | |
| for (let s of sums) { | |
| s.count += node.value; | |
| } | |
| } | |
| return node; | |
| }; | |
| var dumpHead = { | |
| children: tree | |
| }; | |
| console.log(JSON.stringify(sum(dumpHead), null, 2)); //pretty console |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment