Thomas Junk
Thomas Junk

Reputation: 5676

Javascript ES6 Iterator protocol and forEach

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?

Upvotes: 1

Views: 154

Answers (3)

loganfsmyth
loganfsmyth

Reputation: 161627

If you're literally passing through the iterator, you can also do

[Symbol.iterator]() {
  return this._books[Symbol.iterator]();
}

and skip needing the generator in the first place.

Upvotes: 1

Kyle Richardson
Kyle Richardson

Reputation: 5645

I believe the following would be the most idiomatic approach. Please refer to trincot's answer.

*[Symbol.iterator]() {
    for(let book of this._books) {
        yield book;
    }
}

Upvotes: 2

trincot
trincot

Reputation: 350866

I would do it using yield*:

    *[Symbol.iterator]() {
        yield* this._books;
    }

Upvotes: 3

Related Questions