Created
July 5, 2019 13:34
-
-
Save jonasraoni/d81fb6704ca723f6cb8a88537fadd5b2 to your computer and use it in GitHub Desktop.
Performatic list to tree using one loop and map
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
//+ Jonas Raoni Soares Silva | |
//@ http://raoni.org | |
function tree(items) { | |
const tree = []; | |
const map = new Map; | |
for (const item of items) { | |
const placeholder = map.get(item.id); | |
item.children = placeholder ? placeholder.children : []; | |
map.set(item.id, item); | |
//root condition | |
if (item.parentId === item.id) { | |
tree.push(item); | |
} | |
else { | |
const parent = map.get(item.parentId); | |
if (!parent) { | |
map.set(item.parentId, {children: [item]}) | |
} | |
else { | |
parent.children.push(item); | |
} | |
} | |
} | |
return tree; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment