Retrieving generator references
Dmitry Soshnikov
dmitry.soshnikov at gmail.com
Sat Nov 22 20:29:36 PST 2014
On Sat, Nov 22, 2014 at 8:03 PM, Brendan Eich <brendan at mozilla.org> wrote:
> Axel Rauschmayer wrote:
>>
>>
>> A result of this mixing of concerns is that using `next()` to start a
>> generator feels slightly off and that the argument of that first `next()`
>> invocation is completely ignored.
>>
>
> We've discussed a special generator head form to declare that name, but
> not for ES6. For now it's Pythonic, except we decided not to throw if the
> initial .next call passes a non-undefined value.
>
>
Yeah, in Python world (where initial JS generators came from) a technique
to "prime" a generator is often done via a decorator. JS doesn't have
decorators (yet), but it looks like:
```
// A helper decorator that primes the gen.
function coroutine(func) {
return (...args) => {
var gen;
gen = func(...args);
gen.next();
return gen;
};
}
// Actual gen.
let grep = coroutine(pattern => {
let line;
console.log('Looking for ' + pattern);
while (true) {
line = yield;
if (line.indexOf(pattern !== -1)) {
console.log('Found ' + pattern + ' in ' + line);
}
}
return true;
});
// Usage.
let g = grep('Coffee');
g.send('JavaScript');
g.send('CoffeeScript');
```
In Python it would be used as:
```
@coroutine
def grep(pattern):
...
```
Dmitry
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.mozilla.org/pipermail/es-discuss/attachments/20141122/85f1491a/attachment.html>
More information about the es-discuss
mailing list