**
Unpractical use cases - Iterators
What is an iterator? Array Iterator Objects
An Array Iterator is an object, that represents a specific iteration over some specific Array instance object. There is not a named constructor for Array Iterator objects. Instead, Array iterator objects are created by calling certain methods of Array instance objects.
ref : cma-262
Instead of trying to understand it, lets just look at a example
Here we have an object that contains an array, to use the iterator on the array you can simply do something like
To use the iterator to move to the next item in the array you call .next()
console.log(theArrayIterator.next()) // x 5
{ value: 'all', done: false }
{ value: 'the', done: false }
{ value: 'array', done: false }
{ value: 'values', done: false }
{ value: undefined, done: true }
As you can see, each time you call next, it prints the value of the next item in the array, and once it reaches the end of the array it returns done : true
.
It is also possible to customize this behavior
The way this works can be found here Iteration_protocols. If we run the same code we did before
console.log(theArrayIterator.next()) // x 5
{ value: 'all', done: false, arrayIndex: '1 out of 4' }
{ value: 'the', done: false, arrayIndex: '2 out of 4' }
{ value: 'array', done: false, arrayIndex: '3 out of 4' }
{ value: 'values', done: false, arrayIndex: '4 out of 4' }
{ value: 'you have reached the end!', done: true }
The output now contains the arrayIndex
property we added. While writing a twitter scraper with puppeteer I was trying to simulate a never ending twitter feed, so each time the feed would reach the last tweet in the batch, it would call automatically do the ajax call to get the new batch.
Iterators give you the ability to keep track in a very easy to use way and with a little bit of custom code you can greatly enhance that to do really cool stuff.
{ value: 'all', done: false, arrayIndex: '1 out of 4' }
{ value: 'the', done: false, arrayIndex: '2 out of 4' }
{ value: 'right in the middle', done: false,
test: 'so ummm just an update, halfway trough the list' }
{ value: 'array', done: false, arrayIndex: '3 out of 4' }
{ value: 'values', done: false, arrayIndex: '4 out of 4' }
{ value: 'you have reached the end!',
done: true,
test:
'this is just to show you can run a function when the iterator reaches the end oh yeah' }
I am sure there are a million ways to make this code better, but regardless I hope it kind of shows an unpractical way to use iterators.
Comments