/
chunk.go
52 lines (47 loc) · 1.27 KB
/
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
41
42
43
44
45
46
47
48
49
50
51
52
package go2linq
import (
"github.com/solsw/errorhelper"
)
// https://learn.microsoft.com/dotnet/api/system.linq.enumerable.chunk
func factoryChunk[Source any](source Enumerable[Source], size int) func() Enumerator[[]Source] {
return func() Enumerator[[]Source] {
enr := source.GetEnumerator()
c := make([]Source, 0, size)
return enrFunc[[]Source]{
mvNxt: func() bool {
for enr.MoveNext() {
c = append(c, enr.Current())
if len(c) == size {
return true
}
}
return len(c) > 0
},
crrnt: func() []Source {
lc := c
c = make([]Source, 0, size)
return lc
},
rst: func() {
c = make([]Source, 0, size)
enr.Reset()
},
}
}
}
// [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 Enumerable[Source], size int) (Enumerable[[]Source], error) {
if source == nil {
return nil, ErrNilSource
}
if size <= 0 {
return nil, ErrSizeOutOfRange
}
return OnFactory(factoryChunk(source, size)), nil
}
// ChunkMust is like [Chunk] but panics in case of error.
func ChunkMust[Source any](source Enumerable[Source], size int) Enumerable[[]Source] {
return errorhelper.Must(Chunk(source, size))
}