Currently I am sharpening my ES6 skills a bit. I am looking into Iterator/Generator-syntax. I have a working example of
class Library {
constructor(){
this._books = [];
}
addBook(book){
this._books.push(book);
}
get books() {
return this._books;
}
*[Symbol.iterator]() {
for(let i=0; i<this._books.length; i++) {
yield this._books[i];
}
}
}
l = new Library();
l.addBook("Book1");
l.addBook("Book2");
for(let book of l){
console.log(book);
}
Where everything works fine. But my first approach was trying something like
*[Symbol.iterator]() {
this._books.forEach(
book => yield book
)
}
Which is (obviously) not correct. Is there besides looping with for or while a more concise way, to write this?
yieldin a generator function, not in a non-generator function, which is what you are doing in theforEachcallback.yieldin the non-working code is inside the callback to.forEach. That callback function is not a generator.return _books[Symbol.iterator]()should work, but it doesn't. Unsure why. Devil in the implementation, I guess.