Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
462 views
in Technique[技术] by (71.8m points)

typescript: make class objects iterable

How to make Typescript objects iterable? In Python 3 I can do

class EndlessCounter:
    def __init__(self):
        self.count = 0

    def __iter__(self):
        return self

    def __next__(self):
        self.count += 1
        return self.count

but what is the Typescript equivalent of this code?

Thanks!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Javascript supports Iterators and generators, typescript doesn't add much to it: typescript Iterators and Generators.

Your code can be done like this in javascript:

function* generator() {
    let counter = 0;
    while (true) {
        yield counter++;
    }
}

var iterator = generator();
console.log(iterator.next().value); // 0
console.log(iterator.next().value); // 1
console.log(iterator.next().value); // 2

Edit

You can do the same with a class:

class Counter implements Iterator<number> {
    private counter = 0;

    public next(): IteratorResult<number> {
        return {
            done: false,
            value: this.counter++
        }
    }
}

let c = new Counter();
console.log(c.next().value); // 0
console.log(c.next().value); // 1
console.log(c.next().value); // 2

2nd Edit

The first solution with the generator works well with the for/of loop:

function* generator() {
    let counter = 0;
    while (counter < 5) {
        yield counter++;
    }
}
for (let i of generator()) console.log(i);

Prints 0 to 5, however, to do that with an instance you'll need to do:

class Counter implements Iterable<number> {
    private counter = 0;

    public [Symbol.iterator]() {
        return {
            next: function() {
                return {
                    done: this.counter === 5,
                    value: this.counter++
                }
            }.bind(this)
        }
    }
}
let c = new Counter();
for (let i of c) console.log(i);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...