LimitedTransformStream

import { LimitedTransformStream } from "jsr:@ende/streams";

class

class LimitedTransformStream<T> extends TransformStream<T, T>

A TransformStream that will only read & enqueue size amount of chunks.

If options.error is set, then instead of terminating the stream, a RangeError will be thrown when the total number of enqueued chunks is about to exceed the specified size.

Example: size is equal to the total number of chunks

import { LimitedTransformStream } from "@ende/streams/limited-transform-stream";
import { assertEquals } from "@ende/assert";

const stream = ReadableStream.from(["1234", "5678"]);
const transformed = stream.pipeThrough(
  new LimitedTransformStream(2),
);

// All chunks were read
assertEquals(
  await Array.fromAsync(transformed),
  ["1234", "5678"],
);

Example: size is less than the total number of chunks

import { LimitedTransformStream } from "@ende/streams/limited-transform-stream";
import { assertEquals } from "@ende/assert";

const stream = ReadableStream.from(["1234", "5678"]);
const transformed = stream.pipeThrough(
  new LimitedTransformStream(1),
);

// Only the first chunk was read
assertEquals(
  await Array.fromAsync(transformed),
  ["1234"],
);

Example: Throw a RangeError when the total number of chunks is

about to exceed the specified limit

Do this by setting options.error to true.

import { LimitedTransformStream } from "@ende/streams/limited-transform-stream";
import { assertRejects } from "@ende/assert";

const stream = ReadableStream.from(["1234", "5678"]);
const transformed = stream.pipeThrough(
  new LimitedTransformStream(1, { error: true }),
);

await assertRejects(async () => {
  await Array.fromAsync(transformed);
}, RangeError);

Constructors

constructor

new LimitedTransformStream(size: number, options: LimitedTransformStreamOptions = [UNSUPPORTED])

Constructs a new instance.

size: number

The maximum number of chunks to read.

options: LimitedTransformStreamOptions = [UNSUPPORTED]

Options for the stream.

Source