Skip to content

Instantly share code, notes, and snippets.

@jonasraoni
Created July 5, 2019 13:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jonasraoni/d81fb6704ca723f6cb8a88537fadd5b2 to your computer and use it in GitHub Desktop.
Save jonasraoni/d81fb6704ca723f6cb8a88537fadd5b2 to your computer and use it in GitHub Desktop.
Performatic list to tree using one loop and map
//+ 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