Is it possible to define an array iterator that adjusts to your for-of syntax?

Renki Ivanko fatalis.erratum at gmail.com
Mon May 23 15:09:22 UTC 2016


There could be a protocol for defining the shape of the iterator's returns,
but it would need to use functions instead of the loop syntax. I've
previously suggested something like:

```js
iterator[Symbol.shape] = Symbol.shape.entries
```

Then a generic iteration function supporting this interface would know that
the iterator returns entries (key/value pairs) and pass them as separate
parameters to the callback. Something like:

```js
map(iterator, (key, value) => ...)
```

The benefit of this is kind of trivial, though, since all you save yourself
from doing is writing `([key, value])` for the callback function parameters.



R. <http://untu.ms/>

On Mon, May 23, 2016 at 5:47 PM, Jason Orendorff <jason.orendorff at gmail.com>
wrote:

> No, it's not possible.
>
> Oddly enough, when this functionality was first prototyped in
> SpiderMonkey many years ago, the iterator protocol *did* pass a
> boolean to the __iterator__ method (this was before symbols) based on
> the syntax you were using to unpack the results. This feature was not
> super useful in practice, and I always thought it was too subtle --
> the difference in syntax was really not explicit enough to make it
> clear to the programmer what was going on. I'm glad it wasn't
> standardized.
>
> -j
>
>
> On Sun, May 22, 2016 at 12:55 PM, Šime Vidas <sime.vidas at gmail.com> wrote:
> > Say I have an array over which I need to iterate multiple times, but I
> need
> > the index value only some of the time. Is it possible to create a custom
> > iterator which auto-detects when I need the index and feeds me entries()
> > instead of values() in those cases? For example:
> >
> > array[Symbol.iterator] = /* some magic here */
> >
> > for (let elem of array) { /* values() iterator is used automatically */ }
> > for (let [i, elem] of array) { /* entries() iterator is used
> automatically
> > */ }
> >
> >
> > _______________________________________________
> > 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/20160523/28fa9164/attachment.html>


More information about the es-discuss mailing list