-
Notifications
You must be signed in to change notification settings - Fork 17
/
accumulator.go
88 lines (70 loc) · 1.76 KB
/
accumulator.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
package gopark
import (
"fmt"
)
type AccumulateFunc func(x, y interface{}) interface{}
type AccumulatorParam interface {
AddFunc() AccumulateFunc
}
type accumulatorParam struct {
fn AccumulateFunc
}
func (ap accumulatorParam) AddFunc() AccumulateFunc {
return ap.fn
}
var IntAccumulatorParam AccumulatorParam
var ListAccumulatorParam AccumulatorParam
func init() {
IntAccumulatorParam = accumulatorParam{
fn: func(x, y interface{}) interface{} {
return x.(int) + y.(int)
},
}
ListAccumulatorParam = accumulatorParam{
fn: func(x, y interface{}) interface{} {
return append(x.([]interface{}), y)
},
}
}
type Accumulator interface {
Add(interface{})
Value() interface{}
}
type _BaseAccumulator struct {
id int64
param AccumulatorParam
value interface{}
accuChan chan interface{}
}
func (a *_BaseAccumulator) init(initValue interface{}, param AccumulatorParam) {
a.id = newAccumulatorId()
a.value = initValue
a.param = param
a.accuChan = make(chan interface{})
go func() {
for {
localValue := <-a.accuChan
a.value = a.param.AddFunc()(a.value, localValue)
}
}()
}
func (a *_BaseAccumulator) Add(x interface{}) {
a.accuChan <- x
}
func (a *_BaseAccumulator) Value() interface{} {
return a.value
}
func newIntAccumulator(initValue int) Accumulator {
return newAccumulator(initValue, IntAccumulatorParam)
}
func newAccumulator(initValue interface{}, param AccumulatorParam) Accumulator {
a := &_BaseAccumulator{}
a.init(initValue, param)
return a
}
var nextAccuId AtomicInt = 0
func newAccumulatorId() int64 {
nextAccuId.Add(1)
return nextAccuId.Get()
}
var _ = fmt.Println