highland icon indicating copy to clipboard operation
highland copied to clipboard

Idea for discussion: mergeLimit

Open dayoadeyemi opened this issue 11 years ago • 0 comments

When running a large (or potentially infinite) number of asynchronous task based on some sort of event source I find it often very practical to run them in parallel if they involve running asynchronous tasks which aren't taking cpu power (e.g. http requests). However using merge can lead to space leaks as you can continually pull Items from your source without completing any tasks, causing you to run out of memory. Also if you use parallel(n) the buffering forces you to use more memory than necessary as well as blocking you from picking up any new tasks until the very first of your n tasks is completed. I believe this is related to issue #332

the implementation I was thinking of would be

Stream.prototype.mergeLimit = function (n){
    var count = 0;
    var done = false;
    if (!(n > 0)) {
        throw new Error('limit must be a number above 0');
    }
    return this.consume(function(err, stream, push, next){
        if (err) {
            push(err);
        }
        else if (stream === _.nil) {
            // console.log('end of Stream of Streams', count);
            if (count === 0) {
                // console.log('push nil');
                push(null, _.nil);
            }
            done = true;
            return;
        }
        else if (_.isStream(stream)) {
            count = count + 1;
            // console.log('start', stream.id,  count);
            stream.map(push.bind(push, null))
            .toArray(function(){
                count = count - 1;
                // console.log('finished', stream.id, count, done);
                if (done) {
                    if (count === 0) {
                        // console.log('push nil');
                        push(null, _.nil);
                    }
                }
                else {
                    // console.log('call next');
                    next();
                }
            });
        }
        else {
            throw new Error('Expected stream, got ' + typeof stream);
        }
        if (count < n) {
            next();
        }
    });
};

dayoadeyemi avatar Sep 13 '15 11:09 dayoadeyemi