Re: [whatwg/streams] 'Splitter' stream? (#1030)

It's Typescript.  Please don't hold that against me. :-) Below is a translation (still using a class, sorry). 

The goal again is to have a function that allows me to pass in a readable, a test function, and a 'split readable' generator function, and have it do the wiring up so that the generator creates a new readable every time the test function returns true, and routes subsequent writes to a writer associated with that new readable.

Here is my uneducated stab at it, rewritten in JS. It consists of an UnderlyingSink passed to the constructor of a WritableStream. When it gets a write, it checks whether it needs to create a new readable pair using the shouldSplit boolean function. When it does, the idea is to:

a) generate a readable stream from the factory function provided, 
b) create a generic writable stream that we keep around and pass writes through to
c) link the readable and writable together so writes from the writable to go the readable.

Am I just Doing it Wrong? Is there a simpler way?

```
class StreamSplitter {
  
    constructor(shouldSplit, createReadable) {
      this.shouldSplit = shouldSplit;
      this.createReadable = createReadable;
    }
    
    createNewReadable() {
        if (this._writable) {
            this._writable.getWriter().close();
        }
       const readable = this.createReadable();
        // ???
        // How do we create a writable and readable pair
        // such that every write to the writable goes to the readable?
    }

    function start(controller: any) {
        this.createNewReadable();
    },

    function write(chunk: any, controller: any) {
        if (this.shouldSplit(chunk)) {
            this.createNewReadable();
        }
        this._writable.getWriter().write(chunk);
    },

    function close() {
        this._writable.getWriter().close();
    },

    function abort(error: any) {
        this._writable.getWriter().abort();
    }
}
```

-- 
You are receiving this because you are subscribed to this thread.
Reply to this email directly or view it on GitHub:
https://github.com/whatwg/streams/issues/1030#issuecomment-596245452

Received on Sunday, 8 March 2020 19:57:31 UTC