It is a direct follow up of Typing Iterables and Iterators with TypeScript and it would take the Iterator defined in the post, and improve it by making use of generator functions.
Basically, it will show how we can go from a verbose implementation that does not make use of generator functions:
class MakeRange { private _first: number; private _last: number constructor(first, last) { this._first = first; this._last = last; } [Symbol.iterator]() { return { next: () => { if (this._first < this._last) { return {value: this._first++, done: false} } else { return {value: undefined, done: true} } } } } }
Into a more terse and clearer implementation that makes use of generator functions:
class MakeRange { private _first: number private _last: number constructor(first, last) { this._first = first; this._last = last; } *[Symbol.iterator]() { while (this._first < this._last) { yield this._first++ } } }
This post contains the following sections:
- What are generator functions
- Creating generator functions
- Defining Iterator with generator functions
Meaning, we are going to first look at what generator functions are, then we see the various syntaxes for creating them, and finally we bring them to use in simplifying how we define iterables and iterators.
Let's get started.