-
Notifications
You must be signed in to change notification settings - Fork 2
/
node.go
72 lines (55 loc) · 1.1 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
package trie
import "slices"
type node[T any] struct {
childs map[rune]*node[T]
order []rune
parent *node[T]
value T
ok bool
key rune
}
func makeNode[T any](r rune) *node[T] {
return &node[T]{
key: r,
childs: make(map[rune]*node[T]),
}
}
func (n *node[T]) SetValue(val T) {
n.value, n.ok = val, true
}
func (n *node[T]) DropValue() {
var zero T
n.value, n.ok = zero, false
}
func (n *node[T]) HasValue() (ok bool) {
return n.ok
}
func (n *node[T]) Value() (rv T) {
return n.value
}
func (n *node[T]) AddChild(r rune) (rv *node[T]) {
rv = makeNode[T](r)
rv.parent = n
n.childs[r] = rv
n.order = append(n.order, r)
slices.Sort(n.order)
return rv
}
func (n *node[T]) GetChild(r rune) (rv *node[T], ok bool) {
rv, ok = n.childs[r]
return
}
func (n *node[T]) DelChild(r rune) {
if c, ok := n.childs[r]; ok {
delete(n.childs, r)
idx, _ := slices.BinarySearch(n.order, r)
n.order = slices.Delete(n.order, idx, idx+1)
c.parent = nil
}
}
func (n *node[T]) HasChildren() (ok bool) {
return len(n.childs) > 0
}
func (n *node[T]) Parent() (rv *node[T]) {
return n.parent
}