-
Notifications
You must be signed in to change notification settings - Fork 0
/
skip.go
76 lines (59 loc) · 1.89 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
package chans
import "context"
// SkipContext は、Skip の context.Context 版です.
func SkipContext[T any](ctx context.Context, in <-chan T, count int) <-chan T {
return Skip(ctx.Done(), in, count)
}
// SkipWhileContext は、SkipWhile の context.Context 版です.
func SkipWhileContext[T comparable](ctx context.Context, in <-chan T, value T) <-chan T {
return SkipWhile(ctx.Done(), in, value)
}
// SkipWhileFnContext は、SkipWhileFn の context.Context 版です.
func SkipWhileFnContext[T comparable](ctx context.Context, in <-chan T, fn func() T) <-chan T {
return SkipWhileFn(ctx.Done(), in, fn)
}
// Skip -- 指定した個数分、入力用チャネルから値をスキップするチャネルを返します。
func Skip[T any](done <-chan struct{}, in <-chan T, count int) <-chan T {
out := make(chan T)
go func() {
defer close(out)
skipCount := 0
for v := range OrDone(done, in) {
if skipCount < count {
skipCount++
continue
}
select {
case out <- v:
case <-done:
}
}
}()
return out
}
// SkipWhile -- 入力用チャネルから取得した値が指定した値と同一である間、値をスキップし続けるチャネルを返します。
func SkipWhile[T comparable](done <-chan struct{}, in <-chan T, value T) <-chan T {
return SkipWhileFn(done, in, func() T { return value })
}
// SkipWhileFn -- 入力用チャネルから取得した値が指定した関数の戻り値と同一である間、値をスキップし続けるチャネルを返します。
func SkipWhileFn[T comparable](done <-chan struct{}, in <-chan T, fn func() T) <-chan T {
out := make(chan T)
go func(fn func() T) {
defer close(out)
var (
fnResult = fn()
skipEnd = false
)
for v := range OrDone(done, in) {
if !skipEnd && v == fnResult {
continue
}
skipEnd = true
select {
case out <- v:
case <-done:
}
}
}(fn)
return out
}