A custom iterator returns an empty array

Why is the result empty?

var myDogs = function(dogs) { 
 this.dogs = dogs;
 this[Symbol.iterator] = function() {
   let i = -1;
   return {    
    next() {
     i++;
     let j = 0;
     var dog = void(0);
     for (var dog in this.dogs) {
       if (j == i) {
        dog = { dog, hungry: dogs[dog] };
        break;
       } 
       j++;
     }
     var done = !dog;
     return { value: dog, done };
    }
   };
 };
};

var dogs = new myDogs({ buddy: true, hasso: false });
var dogHungryMap = [...dogs];
> dogHungryMap = [];

It seems that I did not understand the concept of iterators, or I am making a completely dumb mistake. Expected Result [{ dog: 'buddy', hungry: true }, { dog: 'hasso': hungry: false }].

http://www.es6fiddle.net/ije6visa/

+4
source share
1 answer

There are two errors in your code:

  • this, in your function next, is an iterator, not an instance myDogs.

  • dog- This is both the key in your iteration and the result. This means dog never undefined at the end of the iteration. You should probably be more careful with the semantics of your variable names.

The solution to these two problems gives the following:

var myDogs = function(dogs) {  
 this.dogs = dogs; 
 let _this = this; 
 this[Symbol.iterator] = function() { 
   let i = -1; 
   return {     
    next() { 
     i++; 
     let j = 0; 
     var dog = void(0); 
     for (var dogName in _this.dogs) { 
       if (j == i) { 
        dog = { dog:dogName, hungry: _this.dogs[dogName] }; 
        break; 
       }  
       j++; 
     } 
     var done = !dog; 
     return { value: dog, done }; 
    } 
   }; 
 }; 
};

But there is a simpler solution:

var myDogs = function(dogs) {
 this[Symbol.iterator] = function() {
   let i = -1;
   return {
    next() {
     i++;
     var dog = Object.keys(dogs)[i];
     if (!dog) return {done:true};
     return {value:{ dog, hungry:dogs[dog] }, done:false};
    }
   };
 };
};

: void(0) .

+5

Source: https://habr.com/ru/post/1624264/


All Articles