What are some real world uses for iterators or generators?


What are some real world uses for iterators or generators?

It just seems like unnecessarily complex code that can be achieved with much simpler code. These are just examples that I found online and I don't know when I should use them. If anything, using iterators/generators seems dangerous because they maintain their own internal state (i.e. the index they are at) and there's no way to access them other than the .done abstraction.

For example

Iterator

function makeIterator(array) { var nextIndex = 0; return { next: function() { return nextIndex < array.length ? {value: array[nextIndex++], done: false} : {done: true}; } }; } let it = makeIterator(['yo', 'ya']); console.log(it.next().value); // 'yo' console.log(it.next().value); // 'ya' console.log(it.next().done); // true 

or you could accomplish the same thing with simpler/less code

let arr = ['yo', 'ya']; let i = 0; console.log(arr[i++]); // 'yo' console.log(arr[i++]); // 'ya' console.log(i >= arr.length); // true 

Generator

function* stringIter(str) { let i = 0; while(i < str.length) yield str[i++]; } let si = stringIter('Hello'); console.log(si.next().value); console.log(si.next().value); console.log(si.next().value); console.log(si.next().done); 

or you could accomplish the same thing with simpler/less code

let i = 0; let str = 'Hello'; console.log(str[i++]); console.log(str[i++]); console.log(str[i++]); console.log(i >= str.length); 

Submitted July 11, 2017 at 01:57PM by IActuallyMeanThis
via reddit http://ift.tt/2ucIzUF

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s