
Something like Scala's for comprehension in Typescript
Problem
val result: Either[String, Int] =
for {
dividend <- Right(42)
divisor <- Right(2)
divisorVerified <- if (divisor != 0) Right(divisor) else Left("Divisor must not be zero!")
} yield dividend / divisor
println(result match {
case Right(value) => value
case Left(error) => error
})
Solution
const result: Result<number, string> =
For._("dividend", success(42))
._("divisor", success(2))
._("divisorVerified", ({divisor}) => divisor != 0 ? success(divisor) : failure("Divisor must not be zero!"))
.yield(({dividend, divisorVerified}) => dividend / divisorVerified)
console.log(isSuccess(result) ? result.value : result.error)
Die Bibliothek beinhaltet auch eine asynchrone Variante, die eine nahtlose Integration von normalen und asynchronen Funktionen mit denselben Monaden erlaubt. Das funktioniert ganz ohne explizites Handling von Promises.
for-comprehension-ts kann mit allen Implementierungen eines Monad Interfaces verwendet werden, welches die Operationen map, flatMap und flatMapAsync umfasst. Die Bibliothek beinhaltet bereits Implementierungen für die folgenden Monaden:

In contrast to pipes this syntax allows programs to be directed acyclic graphs (DAG) whose vertices are named values ( e.g., a = 3) and where edges are functions. The graph will be executed lazily, i.e., before yield is called, there is only a definition of a program. On calling yield, execution will be triggered. Thus, for-comprehension-ts programs can be duplicated, branched and repeated. Operations will only be executed until the first failure, error or absent value occurs. However, this behavioral aspect depends on the used monad.

Contribution
for-comprehension-ts is developed by jambit but not used in production yet. So, please feel free to contribute either directly by adding new features or indirectly by just using it:
- Source code: https://github.com/p3et/for-comprehension-ts
- For comprehension in Scala: https://www.baeldung.com/scala/for-comprehension
---
Author: André Petermann / Senior Software Architect / Office Leipzig
Download Toilet Paper #159: Something like Scala's for comprehension in Typescript (PDF)
You want to write our next ToiletPaper? Apply at jambit!