-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlimit.go
More file actions
40 lines (30 loc) · 700 Bytes
/
Copy pathlimit.go
File metadata and controls
40 lines (30 loc) · 700 Bytes
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
package stream
// Limit returns a stream consisting of the elements of this stream,
// truncated to be no longer than maxSize in length.
func (p *BaseStream[T]) Limit(maxSize int) *BaseStream[T] {
p.C = Limit(p.C, maxSize)
return p
}
// Limit returns a channel consisting of the elements of input channel,
// truncated to be no longer than maxSize in length.
func Limit[T any](input <-chan T, maxSize int) chan T {
output := make(chan T)
if maxSize <= 0 {
go Count(input)
close(output)
return output
}
go func() {
count := 0
for i := range input {
output <- i
count++
if count >= maxSize {
break
}
}
go Count(input)
close(output)
}()
return output
}