Generator issue: exceptions while initializing arguments

Brendan Eich brendan at mozilla.org
Sun Sep 9 15:32:16 PDT 2012


I wanted to leave a clean example (no var and let mixing, either):

function dataSnapshot(aCollection) {
   let snapshot = aCollection.clone();
   let i = 0;
   return {
     next: function () {
       if (i == snapshot.length)
         throw StopIteration;
       return snapshot[i++];
     }
   };
}

(I usually prefer post-increment for loop-ish constructs. Old C hacker 
here.)

Again, anyone trying to avoid the .clone() call would be disappointed. 
Anyone trying to avoid the extra level of function nesting would be 
disappointed. There is irreducible complexity here.

But the generator form is still winning:

function dataSnapshot(aCollection) {
   let snapshot = aCollection.clone();
   return function*() {
     for (let i = 0; i < snapshot.length; i++){
       yield snapshot[i];
     }
   }();
}

IMHO.

/be


Brendan Eich wrote:
> Brendan Eich wrote:
>> function dataSnapshot(aCollection) {
>>   var snapshot = aCollection.clone();
>>   let i = 0;
>
> let i = -1;
>
> rather,
>
>>   return {
>>     next: function () {
>>       if (++i == snapshot.length)
>>         throw StopIteration;
>>       return snapshot[i];
>>     }
>>   };
>> }
>
> or this might run a while!
>
> /be
> _______________________________________________
> es-discuss mailing list
> es-discuss at mozilla.org
> https://mail.mozilla.org/listinfo/es-discuss
>


More information about the es-discuss mailing list