
Lazy, composable, and modular JavaScript - chenglou
https://codewords.recurse.com/issues/four/lazy-composable-and-modular-javascript
======
amelius
A problem I found with generators in Javascript is that you (apparently) can
only yield from within the generator function itself, not from any function
called by that generator. This affects the composability of functions. For
example, say I want to model blocking i/o on top of generators. In that case,
there is a low-level asynchronous mechanism (function) that yields whenever
there is input. A parser function could call this mechanism. And another
function could call the parser. This pattern seems logical, but isn't possible
because suddenly the complete calling hierarchy has to be generator-aware.

~~~
tragic
I don't think this is strictly true: if your parser module also implemented
the iterator/iterable protocols[0], then you could compose them that way. That
may or may not be good enough for a particular use case.

In order to get my head around all this stuff, I made a trivial little toy
library using generators for basic lazy sequences, and providing some basic
stuff from the lodash/underscore library for them.

I found it was enough to make a kind of wrapper class that would hold a
reference to the generator function, but lazily initialise it only when client
code consumed the iterator, or explicitly forced evaluation. At that point,
clients are aware only of the iterable interface, and not at all of the
implementation details. (Or, they wouldn't be, if the _particular_
implementation details didn't require you to use a polyfill on 90% of browsers
and VMs ;-) )

[0]
[https://developer.mozilla.org/en/docs/Web/JavaScript/Referen...](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Iteration_protocols)

------
Halfman
Nice article but, am I the only one shocked by the lack of semicolons in the
given examples?

~~~
krisdol
Try it! If you learn about why semicolons were recommended for js, it's pretty
easy to avoid writing code that would land you in trouble in the semicolon-
free world. Most likely you wouldn't be getting in trouble in the first place
since most of the examples had me thinking "why would I ever write code like
this?". Besides, I think that recommendation maybe came from a time when the
ASI was unreliable and linters were not common. My eslint is awesome at
keeping me out of trouble.

For good reading, have a look at the linked articles at the bottom here
[http://eslint.org/docs/rules/semi.html](http://eslint.org/docs/rules/semi.html)

~~~
glenjamin
There are a few scenarios where you can get bitten by missing out semicolons.

However, this eslint rule should save you: [http://eslint.org/docs/rules/no-
unexpected-multiline](http://eslint.org/docs/rules/no-unexpected-multiline)

