Skip to content

Instantly share code, notes, and snippets.

@rauschma
Last active May 30, 2022 21:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rauschma/d2c2c7d7ba2307702c1396d934e728d9 to your computer and use it in GitHub Desktop.
Save rauschma/d2c2c7d7ba2307702c1396d934e728d9 to your computer and use it in GitHub Desktop.
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Transformer Test</title>
</head>
<body>
<script type="module">
/**
* @see https://streams.spec.whatwg.org/#example-ts-lipfuzz
*/
class ChunksToLinesTransformer {
#previous = '';
transform(chunk, controller) {
let startSearch = this.#previous.length;
this.#previous += chunk;
while (true) {
const eolIndex = this.#previous.indexOf('\n', startSearch);
if (eolIndex < 0) break;
// line includes the EOL
const line = this.#previous.slice(0, eolIndex+1);
controller.enqueue(line);
this.#previous = this.#previous.slice(eolIndex+1);
startSearch = 0;
}
}
flush(controller) {
if (this.#previous.length > 0) {
controller.enqueue(this.#previous);
}
}
}
const stream = new ReadableStream({
async start(controller) {
controller.enqueue('there\nare\nmany\nlines\nhere!');
controller.close(); // FIXES THE BUG THIS CODE HAD
},
});
const transformStream = new TransformStream(new ChunksToLinesTransformer());
const transformed = stream.pipeThrough(transformStream);
const reader = transformed.getReader();
while (true) {
const {value, done} = await reader.read();
if (done) break;
console.log(JSON.stringify(value));
}
// OUTPUT:
// "there\n"
// "are\n"
// "many\n"
// "lines\n"
// "here"
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment