Having null chunks in transform adds extra branch handling to simple transforms, and shouldn't be needed in the stateful transform API.
Alternatively if chunks was never null, you could do end handling with the stateful API by simply adding end logic after consuming the source.
Altered examples from the article:
const toUpperCase = (chunks) => chunks.map(chunk => {
const str = new TextDecoder().decode(chunk);
return new TextEncoder().encode(str.toUpperCase());
});
// Stateful transform with resource cleanup
function createGzipCompressor() {
// Hypothetical compression API...
const deflate = new Deflater({ gzip: true });
return {
async *transform(source) {
for await (const chunks of source) {
for (const chunk of chunks) {
deflate.push(chunk, false);
if (deflate.result) yield [deflate.result];
}
}
// Flush: finalize compression
deflate.push(new Uint8Array(0), true);
if (deflate.result) return [deflate.result];
},
abort(reason) {
// Clean up compressor resources on error/cancellation
}
};
}
Similarly I'm not sure if abort is necessary, could it be a try/catch inside transform instead?
Having
nullchunksin transform adds extra branch handling to simple transforms, and shouldn't be needed in the stateful transform API.Alternatively if
chunkswas nevernull, you could do end handling with the stateful API by simply adding end logic after consuming the source.Altered examples from the article:
Similarly I'm not sure if
abortis necessary, could it be a try/catch insidetransforminstead?