Last active
February 16, 2020 22:36
-
-
Save jsdbroughton/6d4c77cc17dfda0da2725f012fb4027a to your computer and use it in GitHub Desktop.
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
// tree is what is returned post shenanigans. | |
let tree:TreeItem[] = []; | |
// keyMap keeps track of the indexes where parentKeys are found in the keyed but flat array. | |
const keyMap:Map<string, number> = new Map(); | |
treeItemsWithBranches.forEach( ( node ):void => { | |
// nodes with no parents are at root level. | |
// this is not a binary tree, there can be several root level nodes. | |
if ( !node.parentKey ) { | |
tree.push( node ); | |
tree = tree.sort( sortByName ); | |
return; | |
} | |
// this could be left undefined, but Typescript preferred it this way 🧐 | |
let parentIndex = keyMap.get( node.parentKey ); | |
if ( !keyMap.get( node.parentKey ) ) { | |
parentIndex = treeItemsWithBranches.findIndex( ( el ):boolean => el.key === node.parentKey ); | |
keyMap.set( node.parentKey, parentIndex ); | |
} | |
// from here it is just about putting balls in holes. | |
if ( parentIndex !== undefined && parentIndex >= 0 ) { | |
if ( !treeItemsWithBranches[parentIndex] || !treeItemsWithBranches[parentIndex].children ) { | |
treeItemsWithBranches[parentIndex].children = [node]; | |
return; | |
} | |
// object conditional chaining also brings me joy! | |
treeItemsWithBranches[parentIndex]?.children?.push( node ); | |
// i'm keen to improve this as repeatedly sorting feels the most expensive part of this whole exercise. | |
treeItemsWithBranches[parentIndex]?.children?.sort( sortByName ); | |
} | |
} ); | |
return tree; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment