Queria dominar melhor o uso da Stream API, então experimentei com manipulação de strings como exemplo. Isso implementa um TransformStream que divide texto longo em arrays de um tamanho específico.
Implementação
type Ctrl = TransformStreamDefaultController<string[]>;
class TextArrayTransformStream extends TransformStream<string, string[]> { #chunk: string[] = []; #chunkSize: number; #splitReg: RegExp;
constructor(chunkSize: number, maxTextLength: number) { super({ transform: (chunk, controller) => this.#handle(chunk, controller), flush: (controller) => this.#flush(controller), }); this.#chunkSize = chunkSize; this.#splitReg = new RegExp(`.{1,${maxTextLength}}`, "g"); }
#handle(chunk: string, controller: Ctrl): void { for (const str of chunk.match(this.#splitReg) || []) { if (this.#chunk.length >= this.#chunkSize) { controller.enqueue(this.#chunk); this.#chunk = []; } else { this.#chunk.push(str); } } }
#flush(controller: Ctrl): void { if (this.#chunk.length > 0) { controller.enqueue(this.#chunk); } }}Função auxiliar
function toReadableStream(text: string): ReadableStream<string> { return new ReadableStream({ start(controller) { controller.enqueue(text); controller.close(); } });}Exemplo de uso
async function main() { const text = "Texto longo..."; const arrayLength = 5; // Agrupar 5 itens por array const textLength = 10; // Cada elemento tem 10 caracteres
const stream = toReadableStream(text) .pipeThrough(new TextArrayTransformStream(arrayLength, textLength));
const reader = stream.getReader(); while (true) { const { done, value } = await reader.read(); if (done) break;
console.log(value); // string[] é exibido sequencialmente }}Casos de uso
Este padrão é eficaz nos seguintes cenários:
- Ao processar respostas de API LLM em lote
- Ao exibir paginação de texto grande
- Pré-processamento antes de enviar para APIs com limitação de caracteres
Observe que AsyncIterator não está implementado, então a sintaxe for await…of não pode ser usada.
hsb.horse