forked from konimarti/opc
-
Notifications
You must be signed in to change notification settings - Fork 0
/
tree.go
65 lines (58 loc) · 1.37 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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
package opc
import "fmt"
//Tree creates an OPC browser representation
type Tree struct {
Name string
Parent *Tree
Branches []*Tree
Leaves []Leaf
}
//Leaf contains the OPC tag and forms part of the Tree struct for the OPC browser
type Leaf struct {
Name string
Tag string
}
//ExtractBranchByName return substree with name
func ExtractBranchByName(tree *Tree, name string) *Tree {
if tree.Name == name {
return tree
}
for _, b := range tree.Branches {
subtree := ExtractBranchByName(b, name)
if subtree != nil {
return subtree
}
}
return nil
}
//CollectTags traverses tree and collects all tags in string slice
func CollectTags(tree *Tree) []string {
collection := []string{}
for _, l := range tree.Leaves {
collection = append(collection, l.Tag)
}
for _, b := range tree.Branches {
lowerCollection := CollectTags(b)
collection = append(collection, lowerCollection...)
}
return collection
}
//PrettyPrint prints tree in a nice format
func PrettyPrint(tree *Tree) {
fmt.Println(tree.Name)
printSubtree(tree, 1)
}
// printSubtree is a recursive helper function to traverse the tree
func printSubtree(tree *Tree, level int) {
space := ""
for i := 0; i < level; i++ {
space += " "
}
for _, l := range tree.Leaves {
fmt.Println(space, "-", l.Tag)
}
for _, b := range tree.Branches {
fmt.Println(space, "+", b.Name)
printSubtree(b, level+1)
}
}