View
152
Download
0
Category
Preview:
Citation preview
Iterable, Iterator, Generator
By Gaurav Khurana
Iterator Object• Object is an Iterator object when it allows to access items from a
collection one at a time.• Provide next() method to achieve above.• next() method spits out object of this sort {value : ”something” , done : true/false}.
Iterable interface• Object must provide default iteration method which returns an
iterator object.• [Symbol.iterator] is such method in javascript.• Its automatically gets called by for of loop.
Symbol.iterator with other objects
Some objects doesn’t have iterable Interface
For of loop execute iterable interface
Log Result
No iterable for Objects?
But previous example restricts us to use keys as number lets solve that
Quick Recap• The Iterable interface require the implementation of a
[Symbol.iterator] method.• The iterator interface require the implementation of next.• Why next()?
• Because next method’s result has a done property set to true means the iterator has been exhausted and the iteration value.
• Most Iterators implement Iterable interface i.e. most of them have [Symbol.iterator] method.
Let’s simplify the confusing part
Simplifying further, the need of it
Array methods returns Iterable iterator
Generators• Pause Run Pause.• Blocking the asynchronous function calls.• Implementing Iterables.
Conventional function running
Result
How generators are different?• Can be pause as many times and resumed later.• Allowing other code to run during these pause periods.• ES6 generator functions are "cooperative" in their concurrency
behavior which basically indicates that a process (in our case, a function) itself chooses when it will allow an interruption, so that it can cooperate with other code.• Use yield keyword to pause itself.
Syntax please ?
Generators produce iterables
Communicating with Generators
Where can we use them?
Two way communication with Generator
Array index using for of loop?
Generators can help attaining array index using for of
Error Handling
Reverse Direction Error Handling
Reverse error handling continue
Delegating Generators with yield*
Delegating and accepting returned value
Generator can be used for async ajax
Using generator for async
Recommended