1

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?

13
  • 4
    @shash678 wild-ass guess. Commented Nov 10, 2017 at 21:27
  • 2
    You have to use yield in a generator function, not in a non-generator function, which is what you are doing in the forEach callback. Commented Nov 10, 2017 at 21:27
  • 1
    Your yield in the non-working code is inside the callback to .forEach. That callback function is not a generator. Commented Nov 10, 2017 at 21:28
  • 1
    @Will How is WAG related? You really should take care of your ass ...? Commented Nov 10, 2017 at 21:28
  • 1
    It seems return _books[Symbol.iterator]() should work, but it doesn't. Unsure why. Devil in the implementation, I guess. Commented Nov 10, 2017 at 21:38

3 Answers 3

3

I would do it using yield*:

    *[Symbol.iterator]() {
        yield* this._books;
    }
Sign up to request clarification or add additional context in comments.

2 Comments

I learn something almost every time I see one of your post. Keep up the good work!
Whoha. Nice! That's the sort of code, I was looking for.
2

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;
    }
}

2 Comments

Okay! Seems legit. at least nicer, than what I first tried.
trincot's answer is better.
1

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.

1 Comment

Yes, you are right. But the point was more of playing with syntax and expressiveness of the language to get a feeling for what works in which way. I saw the Generator example and began toying around. Not that the code makes any bigger "sense" ;-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.