Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,11 @@ export function takeStream(count) {

let taken = 0;
return new TransformStream({
start(controller) {
if (count === 0) {
controller.terminate();
}
},
transform(chunk, controller) {
if (taken < count) {
taken += 1;
Expand Down
2 changes: 2 additions & 0 deletions readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,8 @@ Returns a `TransformStream` that only passes chunks where `function_` returns `t

### takeStream(count)

A count of zero closes the readable side immediately, without waiting for upstream data.

Returns a `TransformStream` that passes only the first `count` chunks then terminates.

### batchStream(size)
Expand Down
20 changes: 20 additions & 0 deletions regression.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import test from "ava";
import { takeStream } from "./index.js";

test("takeStream(0) closes without waiting for an upstream chunk", async (t) => {
const transform = takeStream(0);
const reader = transform.readable.getReader();
let timeout;
try {
const result = await Promise.race([
reader.read(),
new Promise((resolve) => {
timeout = setTimeout(() => resolve("still pending"), 100);
}),
]);
t.deepEqual(result, { done: true, value: undefined });
} finally {
clearTimeout(timeout);
await reader.cancel();
}
});
Loading