How to make an iterator out of an ES6 class

后端 未结 6 1156
挽巷
挽巷 2021-01-30 10:21

How would I make an iterator out of an ES6 class in the same manner as JS1.7 SomeClass.prototype.__iterator__ = function() {...} syntax?

[EDIT 16:00]

<
6条回答
  •  无人及你
    2021-01-30 10:44

    Example of an ES6 iterator class that stores in a sub-object:

    class Iterator {
        data;
    
        constructor(data = {}) {
            this.data = JSON.parse(JSON.stringify(data));
        }
    
        add(key, value) { this.data[key] = value; }
    
        get(key) { return this.data[key]; }
    
        [Symbol.iterator]() {
            const keys = Object.keys(this.data).filter(key => 
            this.data.hasOwnProperty(key));
            const values = keys.map(key => this.data[key]).values();
            return values;
        }
    }
    

提交回复
热议问题