-
Notifications
You must be signed in to change notification settings - Fork 2
/
drop_chan.go
43 lines (37 loc) · 866 Bytes
/
drop_chan.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
package pipe
import (
"fmt"
"reflect"
)
// DropChan is of type: func(num int, input chan T) chan T.
// Drop a given number of items from the input chan. After that number has been
// dropped, the rest are passed straight through.
func DropChan(num int, input interface{}) interface{} {
inputValue := reflect.ValueOf(input)
if inputValue.Kind() != reflect.Chan {
panic(fmt.Sprintf("DropChan called on invalid type: %s", inputValue.Type()))
}
output := reflect.MakeChan(inputValue.Type(), 0)
var count int
go func() {
// drop num items
for count = 0; count < num; count++ {
_, ok := inputValue.Recv()
if !ok {
// channel closed early
output.Close()
return
}
}
// Return the rest
for {
item, ok := inputValue.Recv()
if !ok {
break
}
output.Send(item)
}
output.Close()
}()
return output.Interface()
}