Created
May 14, 2017 12:56
-
-
Save mpj/3e42ff23548625eff42307dbdc28b499 to your computer and use it in GitHub Desktop.
Maketree for recursion episode, more functional and with better time complexity
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 createChildLookupTable = categories => | |
categories.reduce((lookup, child) => | |
Object.assign({}, lookup, { | |
[child.parent]: (lookup[child.parent] || []).concat(child) | |
}), {}) | |
const makeTree = (childLookup, parent) => | |
(childLookup[parent] || []).reduce((node, child) => | |
Object.assign({}, node, { | |
[child.id]: makeTree(childLookup, child.id) | |
}), {}) | |
console.log(makeTree(createChildLookupTable([ | |
{ id: 'animals', parent: 'root' }, | |
{ id: 'dogs', parent: 'animals' }, | |
{ id: 'cats', parent: 'animals' }, | |
{ id: 'chiuaua', parent: 'dogs' }, | |
{ id: 'labrador', parent: 'dogs' }, | |
{ id: 'siamese', parent: 'cats' }, | |
{ id: 'munchkin', parent: 'cats' } | |
]), 'root')) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
v nice.