/
tree.go
48 lines (40 loc) · 1.09 KB
/
tree.go
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
package gobreak
import (
"strings"
linq "github.com/ahmetalpbalkan/go-linq"
)
type TreePath interface {
GetMc() string
GetUri() string
GetQz() int
}
type TreeNode struct {
Mc string
Uri string
M T
Nodes []*TreeNode
}
func newTreeNode(m TreePath) *TreeNode {
return &TreeNode{m.GetMc(), m.GetUri(), m, make([]*TreeNode, 0)}
}
func BuildTree(src T) []*TreeNode {
root := &TreeNode{"", "", nil, make([]*TreeNode, 0)}
buildTreeNodes(src, root, "")
return root.Nodes
}
func buildTreeNodes(src T, r *TreeNode, prefix string) {
results := queryChildren(linq.From(src), prefix)
for _, it := range results {
child := newTreeNode(it.(TreePath))
r.Nodes = append(r.Nodes, child)
buildTreeNodes(src, child, it.(TreePath).GetUri()+".")
}
}
func queryChildren(q linq.Query, prefix string) []interface{} {
return q.Where(func(s interface{}) bool {
last := strings.TrimPrefix(s.(TreePath).GetUri(), prefix)
return strings.HasPrefix(s.(TreePath).GetUri(), prefix) && !strings.Contains(last, ".")
}).OrderBy(func(a interface{}) interface{} {
return a.(TreePath).GetQz()
}).Results()
}