-
Notifications
You must be signed in to change notification settings - Fork 3
/
flatten.go
83 lines (72 loc) · 1.5 KB
/
flatten.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
package gollection
import (
"fmt"
"reflect"
)
func (g *gollection) Flatten() *gollection {
if g.err != nil {
return &gollection{err: g.err}
}
if g.ch != nil {
return g.flattenStream()
}
return g.flatten()
}
func (g *gollection) flatten() *gollection {
sv, err := g.validateSlice("Flatten")
if err != nil {
return &gollection{err: err}
}
currentType, err := g.validateSliceOfSlice("Flatten")
if err != nil {
return &gollection{err: err}
}
// init
ret := reflect.MakeSlice(currentType, 0, sv.Len())
for i := 0; i < sv.Len(); i++ {
v := sv.Index(i).Interface()
svv := reflect.ValueOf(v)
for j := 0; j < svv.Len(); j++ {
ret = reflect.Append(ret, svv.Index(j))
}
}
return &gollection{
slice: ret.Interface(),
err: nil,
}
}
func (g *gollection) flattenStream() *gollection {
next := &gollection{
ch: make(chan interface{}),
}
var initialized bool
go func() {
for {
select {
case v, ok := <-g.ch:
if ok {
// initialze next stream type
if !initialized {
currentType := v.(reflect.Type).Elem()
if currentType.Kind() != reflect.Slice {
next.ch <- fmt.Errorf("gollection.Flatten called with non-slice-of-slice value of type %s", currentType)
}
next.ch <- currentType
initialized = true
continue
}
svv := reflect.ValueOf(v)
for j := 0; j < svv.Len(); j++ {
next.ch <- svv.Index(j).Interface()
}
} else {
close(next.ch)
return
}
default:
continue
}
}
}()
return next
}