Proposal: for-of-withas a way to provide a value to the generator
Michał Wadas
michalwadas at gmail.com
Mon Aug 21 11:07:18 UTC 2017
Communication by mutating shared variables is not a solution.
On 21 Aug 2017 12:47 pm, "Naveen Chawla" <naveen.chwl at gmail.com> wrote:
> Currently you can set one or more variables outside the scope of the
> generator function during iteration, which the generator function can read.
> Is this so bad?
>
> On Mon, 21 Aug 2017 at 15:24 Marius Gundersen <gundersen at gmail.com> wrote:
>
>> 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
>> _______________________________________________
>> es-discuss mailing list
>> es-discuss at mozilla.org
>> https://mail.mozilla.org/listinfo/es-discuss
>>
>
> _______________________________________________
> es-discuss mailing list
> es-discuss at mozilla.org
> https://mail.mozilla.org/listinfo/es-discuss
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.mozilla.org/pipermail/es-discuss/attachments/20170821/5fcc7310/attachment.html>
More information about the es-discuss
mailing list