This repository has been archived by the owner on May 25, 2021. It is now read-only.
forked from cookingkode/worktree
-
Notifications
You must be signed in to change notification settings - Fork 3
/
worktree.go
86 lines (65 loc) · 1.88 KB
/
worktree.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
package worktree
type CommandTree struct {
Reducer func(inp []interface{}) interface{}
LeafFunctions []func(inp interface{}) interface{}
LeafFunctionsInput []interface{}
nChildren int
LeafFunctionsOutput []interface{}
}
type LeafFunc func(inp interface{}) interface{}
func (t *CommandTree) AddMapper(f func(inp interface{}) interface{}, input interface{}) int {
t.LeafFunctions = append(t.LeafFunctions, f)
t.LeafFunctionsInput = append(t.LeafFunctionsInput, input)
temp := t.nChildren
t.nChildren += 1
return temp
}
func (t *CommandTree) AddReducer(f func(inp []interface{}) interface{}) {
t.Reducer = f
}
//type Inputs map[string]interface{}
type ResultFunction struct {
Child int
//Result reflect.Value
Result interface{}
}
func (t *CommandTree) RunMergeAsync(_ interface{}) interface{} {
// Execcute the tree
channel := make(chan ResultFunction, t.nChildren)
defer close(channel)
for i, f := range t.LeafFunctions {
go wrap(channel, i, f, t.LeafFunctionsInput[i])
}
remaining := t.nChildren
for remaining > 0 {
result := <-channel
remaining -= 1
res := make([]interface{}, 2)
res[0] = result.Result
res[1] = result.Child
t.Reducer(res)
}
return nil
}
func (t *CommandTree) Run(_ interface{}) interface{} {
// Execcute the tree
channel := make(chan ResultFunction, t.nChildren)
defer close(channel)
t.LeafFunctionsOutput = make([]interface{}, t.nChildren)
for i, f := range t.LeafFunctions {
go wrap(channel, i, f, t.LeafFunctionsInput[i])
}
remaining := t.nChildren
for remaining > 0 {
result := <-channel
remaining -= 1
t.LeafFunctionsOutput[result.Child] = result.Result
}
return t.Reducer(t.LeafFunctionsOutput)
}
func wrap(c chan ResultFunction, child int, todo func(inp interface{}) interface{}, inp interface{}) {
var result ResultFunction
result.Result = todo(inp)
result.Child = child
c <- result
}