![]() |
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. IteratorsAn 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:
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.
Output: 1 GeneratorsGenerators 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.
Output: 1 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.
Output: 0 Difference between Iterator and Generator
ConclusionA 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. |
Reffered: https://www.geeksforgeeks.org
TypeScript |
Related |
---|
![]() |
![]() |
![]() |
![]() |
|
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 17 |