File tree Expand file tree Collapse file tree 1 file changed +22
-4
lines changed
packages/node/tests/_helpers Expand file tree Collapse file tree 1 file changed +22
-4
lines changed Original file line number Diff line number Diff line change 11import { Readable } from 'stream' ;
22import { ChunkSplitter } from '../../src/streams/chunkifier.js' ;
33
4+ /**
5+ * Trims array from right until `predicate` returns `false`.
6+ * @returns Trimmed array.
7+ */
8+ function trimRightIf < T > ( t : T [ ] , predicate : ( t : T ) => boolean ) {
9+ for ( let i = t . length - 1 ; i >= 0 ; i -- ) {
10+ if ( predicate ( t [ i ] ) ) {
11+ continue ;
12+ }
13+
14+ return t . slice ( 0 , i + 1 ) ;
15+ }
16+
17+ return [ ] ;
18+ }
19+
420export async function splitToEnd ( readable : Readable , splitter : ChunkSplitter ) {
521 const results : Buffer [ ] [ ] = [ [ ] ] ;
622
723 for await ( let chunk of readable ) {
824 while ( chunk ) {
925 const [ c1 , c2 ] = splitter ( chunk , readable . readableEncoding ?? 'utf-8' ) ;
1026 results [ results . length - 1 ] . push ( c1 ) ;
11- if ( ! c2 ?. length ) {
12- break ;
13- } else if ( c2 ) {
27+ if ( c2 ) {
1428 chunk = c2 ;
1529 results . push ( [ ] ) ;
1630 } else {
@@ -19,7 +33,11 @@ export async function splitToEnd(readable: Readable, splitter: ChunkSplitter) {
1933 }
2034 }
2135
22- return results . map ( ( b ) => Buffer . concat ( b ) ) ;
36+ // Remove all trailing empty arrays
37+ return trimRightIf (
38+ results . map ( ( b ) => Buffer . concat ( b ) ) ,
39+ ( t ) => ! t . length ,
40+ ) ;
2341}
2442
2543export function * chunkify ( chunk : Buffer , length : number ) {
You can’t perform that action at this time.
0 commit comments