-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathchunk.go
40 lines (37 loc) · 810 Bytes
/
chunk.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
package go2linq
import (
"iter"
"github.com/solsw/errorhelper"
)
// [Chunk] splits the elements of a sequence into chunks of size at most 'size'.
//
// [Chunk]: https://learn.microsoft.com/dotnet/api/system.linq.enumerable.chunk
func Chunk[Source any](source iter.Seq[Source], size int) (iter.Seq[[]Source], error) {
if source == nil {
return nil, errorhelper.CallerError(ErrNilSource)
}
if size <= 0 {
return nil, errorhelper.CallerError(ErrSizeOutOfRange)
}
return func(yield func([]Source) bool) {
next, stop := iter.Pull(source)
defer stop()
for {
ss := make([]Source, 0, size)
for range size {
s, ok := next()
if !ok {
break
}
ss = append(ss, s)
}
if len(ss) == 0 {
return
}
if !yield(ss) {
return
}
}
},
nil
}