Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding implementing custom iterators

I am trying to understand Ecmascript 6 iterators and trying to create a data structure which behaves much like native Arrays.

for (let i of [1,2,3]) console.log(i);  //Iterate over data set itself

will output 1,2,3

for (let i of [1,2,3].keys()) console.log(i); //Iterate over a custom iterator from a method

will output 0,1,2, and

var a = [1,2,3];
var keys = [...a.keys()];

will contain [0,1,2] as expected.

Therefore,

console.log([1,2,3].keys().next());

will output Object {value: 0, done: false}

Now I created a new type of data and tried to make it behave the same way.

var myDogs = function(dogs) {
 this.dogs = dogs;
 this[Symbol.iterator] = () => {
   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};
    }
   };
 };
 this.dogsNames = () => {
  return {
   [Symbol.iterator]() {
     let i = -1;
     return {
      next() {
       i++;
       var dog = Object.keys(dogs)[i];
       if (!dog) return {done:true};
       return {value: dog, done:false};
      }
     };
   }
  }
 }
};

var dogs = new myDogs({ buddy: true, hasso: false });

This works as expected (a custom iterator - thank you):

var dogHungryMap = [...dogs];
dogHungryMap == [{ dog: 'buddy', hungry: true }, { dog: 'hasso': hungry: false }]

The iterator dogsNames() works almost as expected. This is OK:

var names = [...dogs.dogsNames()];
names == ["buddy", "hasso"]

But this does not:

dogs.dogsNames().next()
VM19728:2 Uncaught TypeError: dogs.dogsNames(...).next is not a function(…)

Why and how can I reproduce the behavior of native arrays?

like image 757
Liglo App Avatar asked Jan 07 '23 20:01

Liglo App


1 Answers

Because dogsNames() returns an object which has an iterator as a key. So you can use for...of over dogsNames, but to access next() directly you need to access the iterator function declared on the object like so:

dogsNames()[Symbol.iterator]().next()

Babel REPL Example

And for completeness, the full code for sharing next() function:

var myDogs = function(dogs) {
 this.dogs = dogs;
 let i = -1;
 var iter = {
   next() {
     i++;
     var dog = Object.keys(dogs)[i];
     if (!dog) return {done:true};
     return {value:{ dog, hungry:dogs[dog] }, done:false};
   }
 }
 this[Symbol.iterator] = () => iter;
 this.next = iter.next;
};
var dogList = new myDogs({
  dog1: "no",
  dog2: "yes"
});
for(const x of dogList) console.log(x);
console.log(dogList.next());
console.log(dogList.next());
like image 196
CodingIntrigue Avatar answered Jan 16 '23 18:01

CodingIntrigue