javascript-coroutines icon indicating copy to clipboard operation
javascript-coroutines copied to clipboard

small improvement to coroutine function

Open hfmanson opened this issue 3 years ago • 1 comments

Return the value of o.next(x)

function coroutine(f) {
    var o = f();
    o.next();
    return function(x) {
        return o.next(x);
    }
}

hfmanson avatar Mar 06 '22 23:03 hfmanson

I like this, except for the fact that the value from the first o.next() disappears, which I think could lead to some confusion.

I.e. if the coroutine is yielding values, then it's probably best to explicitly make the first next() call, in which case the wrapper would just be:

function coroutine(f) {
    var o = f();
    return function(x) {
        return o.next(x);
    }
}

…or even shorter, come to think of it:

function coroutine(f) {
    var o = f();
    return o.next.bind(o);
}

Since this particular article is only about one-way coroutines which receive events but don't yield values, I think I'll just leave it as-is, but I'm glad this little discussion exists here now too

hrldcpr avatar Mar 07 '22 17:03 hrldcpr