Iterators
An iterator is an object that, when asked for a value, gives a sequence of values one by one, it adheres to the following protocol:
The object must have a next() method which will return an object also has two properties:
value
: The next value in a sequence.done
: A Boolean indicating if this is true, whether the process is depleted or not.
Example: In this example, a SimpleIterator class has been used here to generate a series of numbers from start to end making use of next() method, the sequence is advanced each time the next() is called until it is finished.
class SimpleIterator {
private current: number;
private end: number;
constructor(start: number, end: number) {
this.current = start;
this.end = end;
}
public next(): IteratorResult<number> {
if (this.current <= this.end) {
return { value: this.current++, done: false };
} else {
return { value: null, done: true };
}
}
}
const iterator = new SimpleIterator(1, 5);
let result = iterator.next();
while (!result.done) {
console.log(result.value);
result = iterator.next();
}
Output:
1
2
3
4
5
Iterators & Generators in TypeScript
Iterators and generators are powerful features in TypeScript (and JavaScript) that allow for the creation and manipulation of sequences of values in a lazy, efficient manner, in this article we shall give a detailed account of what these concepts are all about and how to implement them in TypeScript.