Javascript Iterator create multiple iterators from iterable

Introduction

To allow for creating multiple iterators from a single iterable, return an iterator object with the counter variables available through a closure:

class Counter {//from  w  ww  .  j a  v a2s  . c  o m
    constructor(limit) {
        this.limit = limit;
    }

    [Symbol.iterator]() {
        let count = 1,
            limit = this.limit;
        return {
            next() {
                if (count <= limit) {
                    return {
                        done: false,
                        value: count++
                    };
                } else {
                    return {
                        done: true,
                        value: undefined
                    };
                }
            }
        };
    }
}

let counter = new Counter(3);

for (let i of counter) {
    console.log(i);
}
// 1 
// 2 
// 3 
for (let i of counter) {
    console.log(i);
}
// 1 
// 2 
// 3 



PreviousNext

Related