Proposal: for-of-withas a way to provide a value to the generator
Marius Gundersen
gundersen at gmail.com
Mon Aug 21 09:53:38 UTC 2017
Generators today can both "send" a value and "receive" a value from their
consumer, so they can act as an interactive iterable. See for example
[fibonacci with reset](
https://developer.mozilla.org/en/docs/Web/JavaScript/Guide/Iterators_and_Generators#Advanced_generators
)
While generators are "producers" of values, the for-of statement acts as a
"consumer" of these values. But unfortunately the for-of cannot send values
back to the generator:
```js
for(const value of fibonacci()){
console.log(value);
//no way to reset it :(
}
```
I propose a for-of-with statement, like so:
```js
let feedback = false;
for(const value of fibonacci() with feedback){
console.log(value)
feedback = value == 8;
}
```
Note that the variable has to be defined before the for-of-with statement,
but the initial value will not be seen inside the generator until
[function.sent](
https://github.com/allenwb/ESideas/blob/master/Generator%20metaproperty.md)
is implemented.
The babel output of the for-of-with statement would be the following:
```js
var reset = false;
var _iteratorNormalCompletion = true;
var _didIteratorError = false;
var _iteratorError = undefined;
try {
for (var _iterator = fibonacci()[Symbol.iterator](), _step;
!(_iteratorNormalCompletion = (_step = _iterator.next(reset)).done);
_iteratorNormalCompletion = true) {
var value = _step.value;
console.log(value);
reset = value == 8;
}
} catch (err) {
_didIteratorError = true;
_iteratorError = err;
} finally {
try {
if (!_iteratorNormalCompletion && _iterator.return) {
_iterator.return();
}
} finally {
if (_didIteratorError) {
throw _iteratorError;
}
}
}
```
Marius Gundersen
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.mozilla.org/pipermail/es-discuss/attachments/20170821/02633bff/attachment-0001.html>
More information about the es-discuss
mailing list