dominictarr/pull-mux-demux — pull request #2 by alligator-io (2014-08-06 03:15:23+00:00)
Title: _streams/streams objects leads to memory leaks

The issue is that when a stream "end" event is received it is not deleted from the streams / _streams objects

## Tested with:
* in index.js
```javascript
setInterval(function(){
console.log('STREAMS',streams)
console.log('_STREAMS',_streams)
},2000);
```
* and run test script
```
node test/index.js
```

## Changes
### Before
```javascript
function createPairs (id) {
//this needs to be negative on responses
//so we can handle streams from both sides.

if(!streams[id]) {
var p = pair()
var q = pair()
streams[id] = {
source: p.source,
sink: q.sink
}
_streams[id] = {
//this is the 'incoming' stream
//it has a negative id. piped into the connection.
source: pull(q.source, u.wrap(id)),
//this is the 'outgoing' stream,
//it has a positive id.
sink: pull(u.unwrap(id*-1), p.sink)
}

sources.add(_streams[id].source)
}
}
```

### Result
```

STREAMS { '1': { source: [Function: source], sink: [Function: sink] } }
_STREAMS { '1': { source: [Function], sink: [Function] } }

STREAMS { '-1': { source: [Function: source], sink: [Function: sink] } }
_STREAMS { '-1': { source: [Function], sink: [Function] } }

```

## after
* I don't know if this is the right way to fix this issue, but the tests works.

```javascript
function createPairs (id) {
//this needs to be negative on responses
//so we can handle streams from both sides.

var cleanup = function (read) {
return function (abort, cb) {
read(abort, function (end, data) {
if(end){
delete streams[id]
delete _streams[id]
}
cb(end, data)
})
}
}

if(!streams[id]) {
var p = pair()
var q = pair()
streams[id] = {
source: pull(p.source,cleanup),
sink: q.sink
}
_streams[id] = {
//this is the 'incoming' stream
//it has a negative id. piped into the connection.
source: pull(q.source,cleanup,u.wrap(id)),
//this is the 'outgoing' stream,
//it has a positive id.
sink: pull(u.unwrap(id*-1), p.sink)
}

sources.add(_streams[id].source)
}
}
```
### Result
```
STREAMS {}
_STREAMS {}

STREAMS {}
_STREAMS {}
```