Last active
February 10, 2020 15:34
-
-
Save allexysleeps/89fb614a4108666bbf64a23785561c5c to your computer and use it in GitHub Desktop.
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
const flattenChildren = (children) => children | |
.reduce( | |
(flattenedNextLevelChildren, child) => [...flattenedNextLevelChildren, ...child.children], | |
[] | |
) | |
function getTreeWidth(tree) { | |
let width = 1 | |
if (!tree.children.length) { | |
return width | |
} | |
let flatChildrenList = tree.children | |
while (true) { | |
if (!flatChildrenList.length) { | |
return width | |
} | |
width = width < flatChildrenList.length ? flatChildrenList.length : width | |
flatChildrenList = flattenChildren(flatChildrenList) | |
} | |
} | |
const width = getTreeWidth({ | |
value: 'root', | |
children: [ | |
{ | |
value: '1_1', | |
children: [] | |
}, | |
{ | |
value: '1_2', | |
children: [ | |
{ | |
value: '1_2_1', | |
children: [] | |
}, | |
{ | |
value: '1_2_2', | |
children: [ | |
{ | |
value: '1_2_1', | |
children: [] | |
}, | |
{ | |
value: '1_2_2', | |
children: [] | |
}, | |
{ | |
value: '1_2_3', | |
children: [] | |
}, | |
] | |
}, | |
{ | |
value: '1_2_3', | |
children: [ | |
{ | |
value: '1_2_1', | |
children: [] | |
}, | |
{ | |
value: '1_2_2', | |
children: [] | |
}, | |
{ | |
value: '1_2_3', | |
children: [] | |
}, | |
{ | |
value: '1_2_1', | |
children: [] | |
}, | |
{ | |
value: '1_2_2', | |
children: [] | |
}, | |
{ | |
value: '1_2_3', | |
children: [] | |
}, | |
] | |
}, | |
] | |
} | |
] | |
}) | |
console.log(width) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment