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.
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.
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
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.