Skip to content

Instantly share code, notes, and snippets.

@mpj
Created May 14, 2017 12:56
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save mpj/3e42ff23548625eff42307dbdc28b499 to your computer and use it in GitHub Desktop.
Save mpj/3e42ff23548625eff42307dbdc28b499 to your computer and use it in GitHub Desktop.
Maketree for recursion episode, more functional and with better time complexity
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'))
@andrew-luhring
Copy link

v nice.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment