1+ import { BasicParallelEnumerable } from "../BasicParallelEnumerable"
2+ import { ArgumentOutOfRangeException } from "../../shared"
3+ import { IParallelEnumerable , ParallelGeneratorType , TypedData } from "../../types"
4+
5+ export const chunk = < TSource > ( source : IParallelEnumerable < TSource > , size : number ) : IParallelEnumerable < TSource [ ] > => {
6+ if ( size < 1 ) {
7+ throw new ArgumentOutOfRangeException ( "index" )
8+ }
9+
10+ let dataFunc : TypedData < TSource [ ] >
11+
12+ switch ( source . dataFunc . type ) {
13+ case ParallelGeneratorType . ArrayOfPromises :
14+ const arrayOfPromises = source . dataFunc . generator
15+ dataFunc = {
16+ type : ParallelGeneratorType . ArrayOfPromises ,
17+ generator : ( ) => {
18+ const chunks : Promise < TSource [ ] > [ ] = [ ]
19+ let yieldChunk = [ ]
20+ for ( const promise of arrayOfPromises ( ) ) {
21+ yieldChunk . push ( promise )
22+
23+ if ( yieldChunk . length === size ) {
24+ chunks . push ( Promise . all ( yieldChunk ) )
25+ yieldChunk = [ ]
26+ }
27+ }
28+
29+ if ( yieldChunk . length ) {
30+ chunks . push ( Promise . all ( yieldChunk ) )
31+ }
32+
33+ return chunks
34+ }
35+ }
36+ break
37+ case ParallelGeneratorType . PromiseOfPromises :
38+ const promiseOfPromises = source . dataFunc . generator
39+ dataFunc = {
40+ type : ParallelGeneratorType . PromiseOfPromises ,
41+ generator : async ( ) => {
42+ const chunks : Promise < TSource [ ] > [ ] = [ ]
43+ let yieldChunk = [ ]
44+ for ( const promise of await promiseOfPromises ( ) ) {
45+ yieldChunk . push ( promise )
46+
47+ if ( yieldChunk . length === size ) {
48+ chunks . push ( Promise . all ( yieldChunk ) )
49+ yieldChunk = [ ]
50+ }
51+ }
52+
53+ if ( yieldChunk . length ) {
54+ chunks . push ( Promise . all ( yieldChunk ) )
55+ }
56+
57+ return chunks
58+ }
59+ }
60+ break
61+ case ParallelGeneratorType . PromiseToArray :
62+ const promiseToArray = source . dataFunc . generator
63+ dataFunc = {
64+ type : ParallelGeneratorType . PromiseToArray ,
65+ generator : async ( ) => {
66+ const chunks : TSource [ ] [ ] = [ ]
67+ let yieldChunk = [ ]
68+ for ( const value of await promiseToArray ( ) ) {
69+ yieldChunk . push ( value )
70+
71+ if ( yieldChunk . length === size ) {
72+ chunks . push ( yieldChunk )
73+ yieldChunk = [ ]
74+ }
75+ }
76+
77+ if ( yieldChunk . length ) {
78+ chunks . push ( yieldChunk )
79+ }
80+
81+ return chunks
82+ }
83+ }
84+ break
85+ }
86+
87+ return new BasicParallelEnumerable ( dataFunc )
88+ }
0 commit comments