Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to loop the JavaScript iterator that comes from generator?

Let's assume that we have following generator:

var gen = function* () {
  for (var i = 0; i < 10; i++ ) {
    yield i;
  }
};

What is the most efficient way to loop through the iterator ? Currently I do it with checking manually if done property is set to true or not:

var item
  , iterator = gen();

while (item = iterator.next(), !item.done) {
  console.log( item.value );
}
like image 731
hsz Avatar asked Dec 17 '15 11:12

hsz


1 Answers

The best way to iterate any iterable (an object which supports @@iterator), is to use for..of, like this

'use strict';

function * gen() {
    for (var i = 0; i < 10; i++) {
        yield i;
    }
}

for (let value of gen()) {
    console.log(value);
}

Or, if you want an Array out of it, then you can use Array.from, like this

console.log(Array.from(gen());
// [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ]
like image 114
thefourtheye Avatar answered Sep 17 '22 23:09

thefourtheye