-
Notifications
You must be signed in to change notification settings - Fork 2
/
drop_while_chan.go
52 lines (42 loc) · 1.01 KB
/
drop_while_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
44
45
46
47
48
49
50
51
52
package pipe
import (
"fmt"
"reflect"
)
// DropWhileChan is of type: func(fn func(T) bool, input chan T) chan T.
// Drop the items from the input chan until the given function returns true.
// After that, the rest are passed straight through.
func DropWhileChan(fn, input interface{}) interface{} {
checkDropWhileFuncType(fn, input)
inputValue := reflect.ValueOf(input)
fnValue := reflect.ValueOf(fn)
if inputValue.Kind() != reflect.Chan {
panic(fmt.Sprintf("DropWhileChan called on invalid type: %s", inputValue.Type()))
}
output := reflect.MakeChan(inputValue.Type(), 0)
go func() {
for {
item, ok := inputValue.Recv()
if !ok {
// input closed, abort
output.Close()
return
}
// check if we should output this
if !fnValue.Call([]reflect.Value{item})[0].Bool() {
output.Send(item)
break
}
}
// send any messages after this
for {
item, ok := inputValue.Recv()
if !ok {
break
}
output.Send(item)
}
output.Close()
}()
return output.Interface()
}