Lurker News
Preferably an elegant snippet rather than an entire (well engineered) codebase.

Comments (380) 116 threads

Show all comments

Showing thread 42 of 116

mceachen1 reply#
I really appreciated and missed Scala's `Some`/`None`/`Option` [1] and `lazy` constructs, so much so that I brought them with me to TypeScript.

Option provides an elegant way to handle parameters or results that may or may not be defined.
Here's a simple Option implementation:
https://gist.github.com/mceachen/75598510275865b8cf88bb2ef80...
With this you can write something like
Opt(possiblyNullResult).flatMap(ea => functionThatRequiresANonNullResultAndReturnsUndefinedOrDefined(ea)).getOrElse(() => someDefaultValue)
And here's a (very) simple implementation of lazy:
https://github.com/photostructure/exiftool-vendored.js/blob/...
The idea of lazy is to allow deferment of expensive operations until they are actually needed.
The above implementation allows for something like:
const service = lazy(makeService)
Which will ensure makeService is only called once, and the first caller will have to wait for the result of makeService(). All subsequent callers re-use the first result.
It's a simple construct, but extremely handy.
[1] https://github.com/scala/scala/blob/v2.13.1/src/library/scal...

mixedCase#
You might want to look into fp-ts. Has plenty of constructs like those, although it now favors piping calling conventions over a fluent API.