With ES6 generators, I see code like this:
var trivialGenerator = function *(array) {
var i,item;
for(var i=0; i < array.length; i++){
item = array[i];
yield item;
};
};
Is it possible to write something more like the code below instead?
var trivialGenerator = function *(array) {
array.forEach(function *(item){
yield item;
});
};
I'm asking because the classic for
loop is an abomination.
No, you can't use yield
inside of the inner function. But in your case you don't need it. You can always use for-of
loop instead of forEach
method. It will look much prettier, and you can use continue
, break
, yield
inside it:
var trivialGenerator = function *(array) {
for (var item of array) {
// some item manipulation
yield item;
}
}
You can use for-of
if you have some manipulations with item inside it. Otherwise you absolutely don't need to create this generator, as array
has iterator
interface natively.