-
Notifications
You must be signed in to change notification settings - Fork 3
/
skip.go
80 lines (67 loc) · 1.2 KB
/
skip.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 (
"fmt"
"reflect"
)
func (g *gollection) Skip(n int) *gollection {
if g.err != nil {
return &gollection{err: g.err}
}
if g.ch != nil {
return g.skipStream(n)
}
return g.skip(n)
}
func (g *gollection) skip(n int) *gollection {
sv, err := g.validateSlice("Take")
if err != nil {
return &gollection{err: err}
}
if n < 0 {
return &gollection{err: fmt.Errorf("gollection.Skip called with invalid argument. should be larger than 0")}
}
limit := sv.Len()
start := n
if limit < start {
start = limit
}
ret := reflect.MakeSlice(sv.Type(), 0, limit-start)
for i := start; i < limit; i++ {
ret = reflect.Append(ret, sv.Index(i))
}
return &gollection{
slice: ret.Interface(),
}
}
func (g *gollection) skipStream(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++
if n < i {
next.ch <- v
}
} else {
close(next.ch)
return
}
default:
continue
}
}
}()
return next
}