-
Notifications
You must be signed in to change notification settings - Fork 3
/
take.go
70 lines (58 loc) · 1.03 KB
/
take.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
package gollection
import "reflect"
func (g *gollection) Take(n int) *gollection {
if g.err != nil {
return &gollection{err: g.err}
}
if g.ch != nil {
return g.takeStream(n)
}
return g.take(n)
}
func (g *gollection) take(n int) *gollection {
sv, err := g.validateSlice("Take")
if err != nil {
return &gollection{err: err}
}
limit := sv.Len()
if n < limit {
limit = n
}
ret := reflect.MakeSlice(sv.Type(), 0, sv.Len())
for i := 0; i < limit; i++ {
ret = reflect.Append(ret, sv.Index(i))
}
return &gollection{
slice: ret.Interface(),
}
}
func (g *gollection) takeStream(n int) *gollection {
next := &gollection{
ch: make(chan interface{}),
}
var initialized bool
go func() {
i := 0
for {
select {
case v, ok := <-g.ch:
// initialize next stream type
if ok && !initialized {
next.ch <- v
initialized = true
continue
}
if ok && i < n {
next.ch <- v
i++
} else {
close(next.ch)
return
}
default:
continue
}
}
}()
return next
}