UNPKG

1.08 kBJavaScriptView Raw
1
2function build(nodes = [], root = { id: 0 }) {
3 if (typeof root != "object") {
4 root = { id: root }
5 }
6
7 root.children = nodes
8 .filter(n => n.parentId == root.id)
9 .map(c => build(nodes, c))
10
11 return root
12}
13
14function find(nodes, childPropName, matchFn) {
15 for (let n of nodes) {
16 if (matchFn(n) === true) {
17 return n
18 }
19
20 if (n[childPropName]) {
21 let f = find(n[childPropName], childPropName, matchFn)
22 if (f)
23 return f
24 }
25 }
26 return
27}
28
29function map(nodes, childPropName, newChildPropName, mapFun) {
30 var ret = []
31 for (let n of nodes) {
32 if (n[childPropName]) {
33 n[newChildPropName || childPropName] = map(n[childPropName], childPropName, newChildPropName, mapFun)
34 if (newChildPropName && newChildPropName != childPropName)
35 delete n[childPropName]
36 }
37 ret.push(mapFun(n))
38 }
39
40 return ret
41}
42
43export default {
44 build,
45 find,
46 map
47}
\No newline at end of file