Skip to content Skip to sidebar Skip to footer

Custom Iterator Returns 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 =

Solution 1:

Two bugs in your code:

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

  • dog is both the key in your iteration and the result. Which means dog is neverundefined at the end of the iteration. You should probably be more careful with the semantic of your variable names.

Solving these two problems gives this:

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's 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};
    }
   };
 };
};

Side note: there's no reason to use void(0) today.

Post a Comment for "Custom Iterator Returns Empty Array"