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

Allen Wirfs-Brock allen at wirfs-brock.com
Sun May 22 22:17:38 UTC 2016


> On May 22, 2016, at 1: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 */ }

The ES internal protocol design assumes that you would to this as follows:

for (let elem of array.entries()) { /* values() iterator is explicitly used */ }
for (let [i, elem] of array.elements()) { /* entries() iterator is explicitly used */ }

No magic is  necessary.

Allen


-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.mozilla.org/pipermail/es-discuss/attachments/20160522/f6adf2f7/attachment.html>


More information about the es-discuss mailing list