Skip to content

Instantly share code, notes, and snippets.

@allexysleeps
Last active February 10, 2020 15:34
Show Gist options
  • Save allexysleeps/89fb614a4108666bbf64a23785561c5c to your computer and use it in GitHub Desktop.
Save allexysleeps/89fb614a4108666bbf64a23785561c5c to your computer and use it in GitHub Desktop.
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