Javascript Class Generator Methods for collection class

Description

Javascript Class Generator Methods for collection class

class Collection {//from  ww  w .ja va  2  s  . c o m

    constructor() {
        this.items = [];
    }

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

var collection = new Collection();
collection.items.push(1);
collection.items.push(2);
collection.items.push(3);

for (let x of collection) {
    console.log(x);
}

This example uses a computed name for a generator method that delegates to the values() iterator of the this.items array.

Any class that manages a collection of values should include a default iterator.

Now, any instance of Collection can be used in a for-of loop or with the spread operator.




PreviousNext

Related