-
Notifications
You must be signed in to change notification settings - Fork 3
/
map.go
85 lines (70 loc) · 1.59 KB
/
map.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
package gollection
import "reflect"
func (g *gollection) Map(f /* func(v <T1>) <T2> */ interface{}) *gollection {
if g.err != nil {
return &gollection{err: g.err}
}
if g.ch != nil {
return g.mapStream(f)
}
return g.map_(f)
}
func (g *gollection) map_(f interface{}) *gollection {
sv, err := g.validateSlice("Map")
if err != nil {
return &gollection{err: err}
}
funcValue, funcType, err := g.validateMapFunc(f)
if err != nil {
return &gollection{err: err}
}
resultSliceType := reflect.SliceOf(funcType.Out(0))
ret := reflect.MakeSlice(resultSliceType, 0, sv.Len())
// avoid "panic: reflect: call of reflect.Value.Interface on zero Value"
// see https://github.com/azihsoyn/gollection/issues/7
if sv.Len() == 0 {
return &gollection{
slice: ret.Interface(),
}
}
for i := 0; i < sv.Len(); i++ {
v := processMapFunc(funcValue, sv.Index(i))
ret = reflect.Append(ret, v)
}
return &gollection{
slice: ret.Interface(),
}
}
func (g *gollection) mapStream(f interface{}) *gollection {
next := &gollection{
ch: make(chan interface{}),
}
funcValue, funcType, err := g.validateMapFunc(f)
if err != nil {
return &gollection{err: err}
}
var initialized bool
go func() {
for {
select {
case v, ok := <-g.ch:
if ok {
// initialize next stream type
if !initialized {
next.ch <- reflect.SliceOf(funcType.Out(0))
initialized = true
continue
}
v := processMapFunc(funcValue, reflect.ValueOf(v)).Interface()
next.ch <- v
} else {
close(next.ch)
return
}
default:
continue
}
}
}()
return next
}