forked from marktext/marktext
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlistToTree.js
More file actions
48 lines (40 loc) · 984 Bytes
/
listToTree.js
File metadata and controls
48 lines (40 loc) · 984 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
class Node {
constructor (item) {
const { parent, lvl, content, slug } = item
this.parent = parent
this.lvl = lvl
this.label = content
this.slug = slug
this.children = []
}
// Add child node.
addChild (node) {
this.children.push(node)
}
}
const findParent = (item, lastNode, rootNode) => {
if (!lastNode) {
return rootNode
}
const { lvl: lastLvl } = lastNode
const { lvl } = item
if (lvl < lastLvl) {
return findParent(item, lastNode.parent, rootNode)
} else if (lvl === lastLvl) {
return lastNode.parent
} else {
return lastNode
}
}
const listToTree = list => {
const rootNode = new Node({ parent: null, lvl: null, content: null, slug: null })
let lastNode = null
for (const item of list) {
const parent = findParent(item, lastNode, rootNode)
const node = new Node({ parent, ...item })
parent.addChild(node)
lastNode = node
}
return rootNode.children
}
export default listToTree