-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathflat_map.go
104 lines (88 loc) · 2.11 KB
/
flat_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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
package gollection
import (
"fmt"
"reflect"
)
func (g *gollection) FlatMap(f /*func(v <T1>) <T2> */ interface{}) *gollection {
if g.err != nil {
return &gollection{err: g.err}
}
if g.ch != nil {
return g.flatMapStream(f)
}
return g.flatMap(f)
}
func (g *gollection) flatMap(f interface{}) *gollection {
sv, err := g.validateSlice("FlatMap")
if err != nil {
return &gollection{err: err}
}
if _, err := g.validateSliceOfSlice("FlatMap"); err != nil {
return &gollection{err: err}
}
funcValue, funcType, err := g.validateFlatMapFunc(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 := sv.Index(i).Interface()
svv := reflect.ValueOf(v)
for j := 0; j < svv.Len(); j++ {
v := processMapFunc(funcValue, svv.Index(j))
ret = reflect.Append(ret, v)
}
}
return &gollection{
slice: ret.Interface(),
err: nil,
}
}
func (g *gollection) flatMapStream(f interface{}) *gollection {
next := &gollection{
ch: make(chan interface{}),
}
funcValue, funcType, err := g.validateFlatMapFunc(f)
if err != nil {
return &gollection{err: err}
}
var initialized bool
go func() {
for {
select {
case v, ok := <-g.ch:
if ok {
if !initialized {
// initialze next stream type
currentType := v.(reflect.Type).Elem()
if currentType.Kind() != reflect.Slice {
next.ch <- fmt.Errorf("gollection.FlatMap called with non-slice-of-slice value of type %s", currentType)
}
next.ch <- reflect.SliceOf(funcType.Out(0))
initialized = true
continue
}
svv := reflect.ValueOf(v)
for j := 0; j < svv.Len(); j++ {
v := processMapFunc(funcValue, svv.Index(j))
next.ch <- v.Interface()
}
} else {
close(next.ch)
return
}
default:
continue
}
}
}()
return next
}