iTranslated by AI
[TS] Understanding Iterators and Generators: A Back-to-Basics Guide
Introduction
Suddenly, can you explain what "Iterators" and "Generators" are?
Have you ever vaguely brushed it off as something like, "It's that array-like thing, right?" (I certainly did).
In this article, I would like to explain "Iterators" and "Generators" while looking at TypeScript samples.
What is an Iterator?
As an explanation, it can be summarized in the following single line.
An "Iterator" is an object generated from an "Iterable" object and returns an "Iterator Result."
...It's hard to tell what that means.
Don't worry, when I first heard this explanation, I had a look on my face like I'd been hit by a bolt from the blue.
Since several unknown terms appeared, I will explain them in order.
It would be great if you could memorize these, but it's perfectly fine to just get a general sense of them by reading through a few times.
Iterator Result
An Iterator Result is an object with two properties: value, which represents the value, and done, which represents whether the iterator has completed.
Therefore, an instance hoge of the following Hoge type can be said to be an iterator result.
type Hoge = {
value: string;
done: boolean;
}
// hoge is an iterator result
const hoge: Hoge = {
value: 'hogehoge',
done: false,
}
Iterator
An iterator is an object that has a next() function.
next() returns the previously mentioned iterator result.
Therefore, the instance hogeIterator of the following HogeIterator type can be called an iterator.
type Hoge = {
value: string;
done: boolean;
}
type HogeIterator = {
next: () => Hoge;
}
// hogeIterator is an iterator
const hogeIterator: HogeIterator = {
next : () => {
return { value: 'hogehoge', done: false }
}
}
What is Iterable?
To be "Iterable" means to be an object that returns the aforementioned iterator by executing [Symbol.iterator]().
The Symbol.iterator mentioned here is a reserved keyword.
Therefore, the instance hogeIterable of the following HogeIterable type can be said to be iterable.
type Hoge = {
value: string;
done: boolean;
}
type HogeIterator = {
next: () => Hoge;
}
type HogeIterable = {
[Symbol.iterator]: () => HogeIterator;
}
// hogeIterable is iterable
const hogeIterable: HogeIterable = {
[Symbol.iterator]: () => {
return {
next : () => {
return { value: 'hogehoge', done: false }
}
}
}
}
Commonly Used Iterable Types
While we don't often consciously think about the word "Iterable" itself, the following types are also iterable:
-
Arraytype -
Stringtype -
Iterator(The iterator itself is also iterable. If[Symbol.iterator]()is executed, it returns itself)
In addition to these, Map and Set are also iterable, and there is also something called a "Generator" that applies the characteristics of iterators.
When to Use Iterators?
Now that we understand the definition, when do we actually use them?
The most common case is when you want to "retrieve values sequentially using something like a loop."
For example, the for...of syntax we frequently use also handles iterators internally.
const arr: string[] = ['hoge', 'fuga', 'puni'];
for(const v of arr) {
// Internally, it retrieves and uses iterator results from arr in order.
// For example, in the first loop, it retrieves
// { value: 'hoge', done: false }
// as the iterator result.
}
Besides this, many syntaxes and notations commonly seen in the world of JavaScript and TypeScript, such as the spread operator and destructuring assignment, often use iterators under the hood.
const arr: string[] = ['hoge', 'fuga', 'puni'];
// By combining with `...`, it creates an "array of values inside all iterator results"
const arr2: string[] = [...arr, 'bazu'];
To be honest, since syntaxes are provided at a level where you can use them without understanding the processing of iterators, it is rare to specifically refer to the value or done of an iterator result within a custom function.
Also, you rarely create an iterator itself from scratch; even if you do, my impression is that in most cases, you would use the Generators mentioned later.
What is a Generator?
A generator refers to an iterator generated from a generator function.
Since another new term has appeared, I will explain it first.
Generator Function
A generator function is a function declared with function*.
You can use yield and yield* inside it.
The behavior of a generator function differs from that of a regular function.
When a generator function is executed, it returns a generator (it only returns the generator and does not execute the process inside the function at this point).
Each time the caller of the function executes next() on the returned generator, it processes the yield statements inside the generator function in sequence.
For example, suppose you have a generator function like this:
function* generatorFunction (name: string) {
console.log("0");
yield name; // 1st yield
console.log("1");
const hoge: {} = { name };
yield hoge; // 2nd yield
console.log("2");
const arr: string[] = ['hoge', 'fuga', name] ;
yield arr; // 3rd yield
console.log("3");
name='finish';
return name;
}
By executing this generator function, a generator is created.
// Generate a generator
const generator = generatorFunction('test');
As mentioned earlier, at this point, the generator function only returns a generator, so the console.log() embedded within generatorFunction is not executed.
Only when you execute next() on the created generator does it execute up to the "first yield."
The value of the iterator result returned by next() will contain the value specified by yield.
// Executing next() runs up to the first yield in generatorFunction
const first = generator.next();
// * At this timing, console.log("0") is executed
console.log(first); // --> { value: 'test', done: false }
Thereafter, each time next() is executed, the process continues sequentially up to the next yield, returning an iterator result each time.
Then, when the execution reaches the end of the generator function, an iterator result with done set to true is returned. At this time, value will contain the value that was returned by the generator function.
// The value of the 2nd yield enters value
console.log(generator.next()) // --> { value: { name: 'test' }, done: false }
// The value of the 3rd yield enters value
console.log(generator.next()) // --> { value: [ 'hoge', 'fuga', 'test' ], done: false }
// Since function execution is finished, done becomes true
console.log(generator.next()) // --> { value: 'finish', done: true }
Generator Composition
You can pass a single value to yield in a generator function, but by specifying yield*, you can pass the "iterator itself."
For example, if you have a generator like the following:
function* generatorFunction2() {
yield 'hoge';
yield 'fuga';
yield 'puni';
}
Since yield is defined three times, it can be called as follows:
const generator = generatorFunction2();
console.log(generator.next()); // --> { value: 'hoge', done: false }
console.log(generator.next()); // --> { value: 'fuga', done: false }
console.log(generator.next()); // --> { value: 'puni', done: false }
console.log(generator.next()); // --> { value: undefiend, done: true }
By rewriting this using yield* as shown below, you can pass the iterator.
*The execution result is the same.
function* generatorFunction2() {
yield* ['hoge', 'fuga', 'puni'];
}
Additionally, since you can pass an iterator to yield*, you can also pass a generator.
In other words, while it is a bit of a redundant expression, you can rewrite the above as follows:
function* generatorFunction1 () {
yield "hoge";
yield "fuga";
yield "puni";
}
// Generate a generator from generatorFunction1
const generator1 = generatorFunction1();
function* generatorFunction2 () {
// Pass the previous generator to yield*
yield* generator1;
}
// Generate a generator from generatorFunction2
const generator2 = generatorFunction2();
// Since an iterator can be passed to for...of, a generator can also be passed
for(const value of generator2) {
console.log(value);
}
// --> "hoge"
// --> "fuga"
// --> "puni"
If the error "Type 'Generator<...>' is not array..." appears
When executing the above source code, an error may occur depending on the contents of tsconfig.
In that case, add "downlevelIteration": true to compilerOptions.
{
"compilerOptions": {
"target": "es5",
"downlevelIteration": true
}
}
When to Use Generators?
Unlike iterators, there are situations where you may need to implement generators yourself if you are creating something detailed.
However, in those cases, it is common to use the property that generators "only return a generator when executed, and then process yield statements sequentially each time next() is called."
What I'm trying to say is that a generator allows a function to be executed while interrupting it at each yield point.
By sandwiching asynchronous processing between these yield points, each process can be handled synchronously.
- For example, the library
redux-saga, which is sometimes used withReactorReactNative, makes use of this property.
Summary
In this article, I explained "Iterators" and "Generators" based on the TypeScript codebase.
To be honest, since each syntax is well-prepared to the extent that it can be handled without understanding the internal behavior, there aren't many opportunities to learn about it.
I think knowledge becomes necessary around the time you start dealing with custom-made generators, so I hope this will be helpful at that time.
Discussion