|
|
|
|
|
by thejsjunky
4868 days ago
|
|
That's essentially what they are. What generators are is making this construct a first class citizen in the language which makes it much easier to manage. Your code as is isn't bad in terms of readability/complexity...but it'd be cleaner as a generator. Then consider how much more complicated it would be if instead your generator needed to alternately return total/count and count/total (or whatever). You'd have to duplicate the two lines that increment total and count (or factor them out), have another send function, and then have code to start swapping @send to the appropriate function...or have some boolean flag to figure out which to do..etc. It gets messy if you introduce even more.
Instead with generators you could write something like: function mySillyGenerator (c) {
var count = c || 0;
var total = 0;
while (true) {
count = yield count/total;
count = yield total/cound
}
}
Generators are a way to make stuff like this simple. In JS you can roll your own iterators, but in many cases it will be cleaner just writing a generator. |
|