Javascript supports Iterators and generators , typescript does not add special meaning to it: typescript Iterators and generators .
Your code can be done as follows 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 the 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 / loop:
function* generator() { let counter = 0; while (counter < 5) { yield counter++; } } for (let i of generator()) console.log(i);
Prints from 0 to 5, however, to do this with the instance you will 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);
Nitzan tomer
source share