@@ -2,6 +2,7 @@ package streams
2
2
3
3
import (
4
4
"context"
5
+ "errors"
5
6
"sync"
6
7
)
7
8
@@ -26,11 +27,11 @@ func New[T any](in []T) <-chan T {
26
27
// the buffer of the channel is set to the number of values and the values are
27
28
// pushed into the channel before returning.
28
29
//
29
- // str, push, close := NewConcurrent(1, 2, 3)
30
- // push(context.TODO(), 4, 5, 6)
31
- // vals, err := All(str)
32
- // // handle err
33
- // // vals == []int{1, 2, 3, 4, 5, 6}
30
+ // str, push, close := NewConcurrent(1, 2, 3)
31
+ // push(context.TODO(), 4, 5, 6)
32
+ // vals, err := All(str)
33
+ // // handle err
34
+ // // vals == []int{1, 2, 3, 4, 5, 6}
34
35
//
35
36
// Use the Concurrent function to create a `push` function for an existing channel.
36
37
func NewConcurrent [T any ](vals ... T ) (_ <- chan T , _push func (context.Context , ... T ) error , _close func ()) {
@@ -104,6 +105,26 @@ func All[T any](in <-chan T, errs ...<-chan error) ([]T, error) {
104
105
return Drain (context .Background (), in , errs ... )
105
106
}
106
107
108
+ var errTakeDone = errors .New ("take done" )
109
+
110
+ // Take receives elements from the input channel until it has received n
111
+ // elements or the input channel is closed. It returns a slice containing the
112
+ // received elements. If any error occurs during the process, it is returned as
113
+ // the second return value.
114
+ func Take [T any ](ctx context.Context , n int , in <- chan T , errs ... <- chan error ) ([]T , error ) {
115
+ out := make ([]T , 0 , n )
116
+ if err := Walk (ctx , func (v T ) error {
117
+ out = append (out , v )
118
+ if len (out ) >= n {
119
+ return errTakeDone
120
+ }
121
+ return nil
122
+ }, in , errs ... ); err != nil && ! errors .Is (err , errTakeDone ) {
123
+ return out , err
124
+ }
125
+ return out , nil
126
+ }
127
+
107
128
// Walk receives from the given channel until it and and all provided error
108
129
// channels are closed, ctx is closed or any of the provided error channels
109
130
// receives an error. For every element e that is received from the input
0 commit comments