🔰make iterables

JSiterationiterable ⟩ make iterables

we can make class/object iterable by letting them:

examples

use generator function to return new iterator.

💾 replit:make class iterable

// an iterable (that can make iterators)
class ValueContainer {

    // private properties
    #values;

    // init
    constructor(...values) {
        this.#values = values;
    }

    // ⭐ "make iterator" method
    // ⭐ use generator function to return new iterator
    *[Symbol.iterator]() {
        for (const value of this.#values) {
            yield value;
        }
    }

}

// main
let container = new ValueContainer(1,2,3);
[...container];        // [ 1, 2, 3 ]

Last updated