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

Decorators for generators?

Open dead-claudia opened this issue 10 years ago • 6 comments

This is the one part I was surprised didn't exist. Every other possibility I can think of is covered with this proposal, but I think generators might have been overlooked.

I have already come across a problem where I needed this functionality, and I ran into issues.

Is there any reason generators shouldn't be decorated?

dead-claudia avatar Jun 19 '15 09:06 dead-claudia

FWIW, here's my use case:

function checkCallable(desc) {
    const original = desc.value
    desc.value = function (f) {
        assertCallable(f, 'f')
        return original.apply(this, arguments)
    }
}

function wrap(desc) {
    const original = desc.value
    desc.value = function () {
        return new Wrapper(original.apply(this, arguments))
    }
}

class Wrapper {
    // ...

    @checkCallable @wrap *map(f) {
        let index = 0
        for (const entry of this) {
            yield f(entry, index++)
        }
    }

    @checkCallable @wrap *filter(f) {
        let index = 0
        for (const entry of self) {
            if (f(entry, index++)) {
                yield entry
            }
        }
    }

    // ...
}

dead-claudia avatar Jun 19 '15 10:06 dead-claudia

:+1: I'm surprised this didn't work already, as generators seem to work just like normal functions for everything else (like static class methods, for example).

rosshadden avatar Aug 15 '15 20:08 rosshadden

We're making an app using KOA, and it was exciting to use decorators to give all of our methods an @verb and and @param. But it seems generator functions don't accept decorators yet. +1 for this feature.

optikalefx avatar Aug 15 '15 20:08 optikalefx

Running into the same issue, trying to decorate generator functions in a Koa app for routing purposes. From another thread, I see this is an issue of ambiguous grammar, but that thread seems to suggest the underlying issue is resolved: https://phabricator.babeljs.io/T2014. Is there a way to get this to work now?

galenwarren avatar Dec 29 '15 03:12 galenwarren

@GalenWarren You are correct (#34). I think the only outstanding part remaining is a PR.

dead-claudia avatar Dec 29 '15 05:12 dead-claudia

Actually this should work and was never limited by the spec, but it does not due to a "bug" in babylon. See also #66.

silkentrance avatar Mar 23 '16 18:03 silkentrance