Skip to content

Commit 10d5be3

Browse files
authored
node: fix splitToEnd function returning invalid chunks in tests (NFC) (#305)
Co-authored-by: Sebastian Alex <sebastian.alex@saucelabs.com>
1 parent 8b32b34 commit 10d5be3

File tree

1 file changed

+22
-4
lines changed

1 file changed

+22
-4
lines changed

packages/node/tests/_helpers/chunks.ts

Lines changed: 22 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,30 @@
11
import { Readable } from 'stream';
22
import { 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+
420
export 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

2543
export function* chunkify(chunk: Buffer, length: number) {

0 commit comments

Comments
 (0)