-
Notifications
You must be signed in to change notification settings - Fork 0
/
gopherwood.go
97 lines (84 loc) · 1.54 KB
/
gopherwood.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
93
94
95
96
97
package gopherwood
func createNode(key string) (chan string, chan string) {
in := make(chan string)
out := make(chan string)
var (
rightTo chan string
rightFro chan string
leftTo chan string
leftFro chan string
)
go func() {
for {
switch <-in {
// get and set are not used but are didactic
case "get":
out <- key
case "set":
key = <-in
case "add":
newKey := <-in
sideTo := &rightTo
sideFro := &rightFro
if key > newKey {
sideTo = &leftTo
sideFro = &leftFro
} else if key == newKey {
continue
}
if *sideTo == nil {
*sideTo, *sideFro = createNode(newKey)
} else {
*sideTo <- "add"
*sideTo <- newKey
}
case "search":
searchKey := <-in
sideTo := &rightTo
sideFro := &rightFro
if key > searchKey {
sideTo = &leftTo
sideFro = &leftFro
} else if key == searchKey {
out <- key
continue
}
if *sideTo == nil {
out <- "nope"
} else {
*sideTo <- "search"
*sideTo <- searchKey
out <- <-*sideFro
}
default:
out <- "what?"
}
}
}()
return in, out
}
type Tree struct {
rootTo chan string
rootFro chan string
}
func (t *Tree) Add(key string) {
if t.rootTo == nil {
t.rootTo, t.rootFro = createNode(key)
} else {
t.rootTo <- "add"
t.rootTo <- key
}
}
func (t *Tree) Search(key string) (response string) {
if t.rootTo != nil {
t.rootTo <- "search"
t.rootTo <- key
response = <-t.rootFro
}
return
}
type Node struct {
key string
left *Node
right *Node
}