-
Notifications
You must be signed in to change notification settings - Fork 1
/
node.go
92 lines (73 loc) · 1.69 KB
/
node.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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
package trie
import "fmt"
// node represents a separate tree node.
type node struct {
key string
children map[byte]*node
data []interface{}
}
func newEmptyNode(key string) *node {
return &node{
key: key,
children: make(map[byte]*node),
}
}
// Member contains prefix's member data.
type Member struct {
Key string
Data interface{}
}
func (n *node) getAllMembers() (mm []Member) {
// append node's data
if len(n.data) != 0 {
for _, v := range n.data {
mm = append(mm, Member{
Key: n.key,
Data: v,
})
}
}
// loop through children
for _, v := range n.children {
mm = append(mm, v.getAllMembers()...)
}
return
}
func (n *node) createPathChildren(parentKey, path string, data interface{}) {
key := path[0]
currentKey := parentKey + string(key)
_, childExists := n.children[key]
if !childExists {
n.children[key] = newEmptyNode(currentKey)
}
cutPath := path[1:len(path)]
if len(cutPath) == 0 {
n.children[key].data = append(n.children[key].data, data)
return
}
n.children[key].createPathChildren(currentKey, cutPath, data)
}
func (n *node) lookupPathChildren(path string) bool {
key := path[0]
_, childExists := n.children[key]
if !childExists {
return false
}
cutPath := path[1:len(path)]
if len(cutPath) == 0 {
return true
}
return n.children[key].lookupPathChildren(cutPath)
}
func (n *node) getChildNodeByPath(path string) (*node, error) {
key := path[0]
childNode, childExists := n.children[key]
if !childExists {
return nil, fmt.Errorf("child by the key %s doesn't exist", string(key))
}
cutPath := path[1:len(path)]
if len(cutPath) == 0 {
return childNode, nil
}
return n.children[key].getChildNodeByPath(cutPath)
}