domenic at domenicdenicola.com (2014-08-26T18:26:14.155Z)
Le 20 août 2014 à 10:42, Andy Wingo <wingo at igalia.com> a écrit :
> This has the disadvantage of starting computation in the generator, of
> course, before it has been asked for.
Indeed. Here is a version that don't start computation early.
```js
const ignoreFirst = genFn => class extends genFn {
next(x) {
delete this.next // next calls to `next` will use directly the super method
super()
return super(x)
}
}
var echo = ignoreFirst(function* echo() {
var x
while (true) {
x = yield x
}
})
var iter = new echo // note: `new` is needed for correct subclassing!
iter.next(4) // {value: 4, done: false}
iter.next(1) // {value: 1, done: false}
iter.next(6) // {value: 6, done: false}
```
Le 20 août 2014 à 10:42, Andy Wingo <wingo at igalia.com> a écrit : > On Tue 19 Aug 2014 08:48, Claude Pache <claude.pache at gmail.com> writes: > >> Le 19 août 2014 à 06:47, Kevin Smith <zenparsing at gmail.com> a écrit : >> >> It appears that the current state of affairs is that the argument >> supplied to the first call of `next` on a newborn generator is >> "ignored and inaccessibe". >> >> Is there any way that the generator function can have access to that >> lost data? >> >> This can be worked around. Basically, ask the generator to advance to >> the first `yield` at instantiation, and retrieve the value of the >> "first" `next()` with that `yield`. For example: > > This has the disadvantage of starting computation in the generator, of > course, before it has been asked for. > Indeed. Here is a version that don't start computation early. ```js const ignoreFirst = genFn => class extends genFn { next(x) { delete this.next // next calls to `next` will use directly the super method super() return super(x) } } var echo = ignoreFirst(function* echo() { var x while (true) { x = yield x } }) var iter = new echo // note: `new` is needed for correct subclassing! iter.next(4) // {value: 4, done: false} iter.next(1) // {value: 1, done: false} iter.next(6) // {value: 6, done: false} ``` —Claude