-
Notifications
You must be signed in to change notification settings - Fork 3
/
filter.go
80 lines (68 loc) · 1.42 KB
/
filter.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
package gollection
import "reflect"
func (g *gollection) Filter(f /* func(v <T>) bool */ interface{}) *gollection {
if g.err != nil {
return &gollection{err: g.err}
}
if g.ch != nil {
return g.filterStream(f)
}
return g.filter(f)
}
func (g *gollection) filter(f interface{}) *gollection {
sv, err := g.validateSlice("Filter")
if err != nil {
return &gollection{err: err}
}
funcValue, funcType, err := g.validateFilterFunc(f)
if err != nil {
return &gollection{err: err}
}
resultSliceType := reflect.SliceOf(funcType.In(0))
ret := reflect.MakeSlice(resultSliceType, 0, sv.Len())
for i := 0; i < sv.Len(); i++ {
v := sv.Index(i)
if processFilter(funcValue, v) {
ret = reflect.Append(ret, v)
}
}
return &gollection{
slice: ret.Interface(),
}
}
func (g *gollection) filterStream(f interface{}) *gollection {
next := &gollection{
ch: make(chan interface{}),
}
funcValue, funcType, err := g.validateFilterFunc(f)
if err != nil {
return &gollection{
err: err,
}
}
var initialized bool
go func() {
for {
select {
case v, ok := <-g.ch:
if ok {
if !initialized {
// initialize next stream type
next.ch <- reflect.SliceOf(funcType.In(0))
initialized = true
continue
}
if processFilter(funcValue, reflect.ValueOf(v)) {
next.ch <- v
}
} else {
close(next.ch)
return
}
default:
continue
}
}
}()
return next
}