Iterators & Generators in TypeScript
Last Updated :
30 May, 2024
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.
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.
JavaScript
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
Generators
Generators are a special kind of function that can stop, and then continue from where it stopped, using this kind of function you can make a function that implements an iterative algorithm only by writing just one function which doesn't have to run its course at a go. They are defined by a function with an * in it and make use of the keyword yield in order to generate a set of numbers.
Example 1: The generatorFunction makes use of the function* syntax in order to return a sequence of numbers from 1 up to 5, here yield keyword will return each number and execution will be paused until next() is called again.
JavaScript
function* generatorFunction() {
yield 1;
yield 2;
yield 3;
yield 4;
yield 5;
}
const generator = generatorFunction();
let result = generator.next();
while (!result.done) {
console.log(result.value);
result = generator.next();
}
Output:
1
2
3
4
5
Example 2: Generators can also accept parameters and return values. Fibonacci generator gives Fibonacci numbers up to a specified limit. Whenever next() is invoked it updates and outputs the next number in the Fibonacci sequence until it reaches the limit and stops there.
JavaScript
function* fibonacci(limit: number) {
let a = 0, b = 1, count = 0;
while (count < limit) {
yield a;
[a, b] = [b, a + b];
count++;
}
}
const fib = fibonacci(5);
for (const value of fib) {
console.log(value);
}
Output:
0
1
1
2
Difference between Iterator and Generator
Aspect | Iterator | Generator |
---|
Creation | Manually implemented using an object with a next method. | Created by using function* and yield . |
---|
State | No intrinsic mechanism to save state between calls. | Maintains its own state by allowing it to pause and resume execution. |
---|
Simplicity | Simpler to implement for basic use cases. | More powerful and also more convenient for complex sequences and asynchronous workflows. |
---|
Conclusion
A greater part of sequences of figures can be effectively operated by TypeScript iterators and generators, when it comes to iteration, iterators only have a simple protocol as their next() method, on the other hand, generators are more superior in providing control over its execution state through yield.
Similar Reads
TypeScript Generic Types TypeScript Generic Types can be used by programmers when they need to create reusable components because they are used to create components that work with various data types and this provides type safety. The reusable components can be classes, functions, and interfaces. TypeScript generics can be u
2 min read
Iterate Over Characters of a String in TypeScript Iterating over characters of a string involves going through them one by one using loops or specific methods. This is useful for tasks like changing or analyzing the content of a string efficiently. Example:Input: string = "Hello Geeks"; Output: H e l l o G e e k sBelow listed methods can be used to
4 min read
TypeScript Decorators TypeScript Decorators are a new and special way of declaring the classes, methods, parameters, and properties. The decorators are defined using the @expression syntax, where the expression will be a function that is to be invoked at the runtime with the information of the decorated declaration. Synt
4 min read
Data types in TypeScript In TypeScript, a data type defines the kind of values a variable can hold, ensuring type safety and enhancing code clarity.Primitive Types: Basic types like number, string, boolean, null, undefined, and symbol.Object Types: Complex structures including arrays, classes, interfaces, and functions.Prim
3 min read
Interfaces in TypeScript TypeScript is a statically typed superset of JavaScript that adds optional types, classes, interfaces, and other features to help developers build robust and maintainable applications. One of the most powerful features of TypeScript is interfaces, which allow you to define the structure of objects,
4 min read
How to use getters/setters in TypeScript ? In TypeScript, getters and setters provide controlled access to class properties, enhancing encapsulation and flexibility.Getters allow you to retrieve the value of a property with controlled logic.Setters enable controlled assignment to properties, often including validation or transformations.Java
5 min read