Created
March 2, 2018 02:48
-
-
Save jptcnde/7cbd8662c7f32d167575d1e32aeedf81 to your computer and use it in GitHub Desktop.
create tree from paths string.
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
const createNode = ([ | |
lvl, text, path, | |
value, | |
key, | |
parentKey, | |
]) => ({ | |
value, | |
lvl, text, path, | |
key, | |
parentKey, | |
children: [], | |
}); | |
const insertNode = (node, data) => { | |
if (data.parentKey === node.key && | |
node.children.every(x => x.key !== data.key)) { | |
node.children.push(data); | |
return node; | |
} | |
return node.children.reduce((acc, n) => | |
insertNode(n, data) && acc, node); | |
}; | |
const createTreeFromPath = (data) => | |
data.reduce((acc, pth) => | |
acc.push(pth.split('/').reduce((prev, txt, lvl) => | |
prev.push([ | |
lvl, txt, pth, | |
pth.split('/').slice(0, lvl + 1).join('/'), | |
`${lvl}--${txt}`, | |
!prev.slice().pop() | |
? null | |
: `${prev[lvl - 1][0]}--${prev[lvl - 1][1]}` | |
]) && prev, []) | |
) && acc | |
, []) | |
.reduce((acc, n) => [...acc, ...n]) | |
.map(n => createNode(n)) | |
.reduce((root, n) => insertNode(root, n, root), { children: [], key: null }); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
usage: