toTransformStream

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

function

function toTransformStream<I, O>(transformer: (src: ReadableStream<I>) => Iterable<O> | AsyncIterable<O>, writableStrategy?: QueuingStrategy<I>, readableStrategy?: QueuingStrategy<O>): TransformStream<I, O>

Convert the generator function into a TransformStream.

transformer: (src: ReadableStream<I>) => Iterable<O> | AsyncIterable<O>

A function to transform. Must return an iterable or async iterable.

writableStrategy?: QueuingStrategy<I>

An object that optionally defines a queuing strategy for the stream's internal buffer between source and transformer.

readableStrategy?: QueuingStrategy<O>

An object that optionally defines a queuing strategy for the stream's output buffer.

Returns

A TransformStream that transforms the source stream as defined by the provided transformer.

Example: Build a transform stream that multiplies each value by 100

import { toTransformStream } from "@ende/streams/to-transform-stream";
import { assertEquals } from "@ende/assert";

const stream = ReadableStream.from([0, 1, 2])
  .pipeThrough(toTransformStream(async function* (src) {
    for await (const chunk of src) {
      yield chunk * 100;
    }
  }));

assertEquals(
  await Array.fromAsync(stream),
  [0, 100, 200],
);

Example: JSON Lines

import { TextLineStream } from "@ende/streams/text-line-stream";
import { toTransformStream } from "@ende/streams/to-transform-stream";
import { assertEquals } from "@ende/assert";

const stream = ReadableStream.from([
  '{"name": "Alice", "age": ',
  '30}\n{"name": "Bob", "age"',
  ": 25}\n",
]);

type Person = { name: string; age: number };

// Split the stream by newline and parse each line as a JSON object
const jsonStream = stream.pipeThrough(new TextLineStream())
  .pipeThrough(toTransformStream(async function* (src) {
    for await (const chunk of src) {
      if (chunk.trim().length === 0) {
        continue;
      }
      yield JSON.parse(chunk) as Person;
    }
  }));

assertEquals(
  await Array.fromAsync(jsonStream),
  [{ "name": "Alice", "age": 30 }, { "name": "Bob", "age": 25 }],
);

Source