blog podcast

Chaining Calls

I don’t really know if it’s worth it, but I’m working with Optionals in this Typescript library that I’m building. Typescript already has its question mark in the type system to mark if something can be null ornot, just like they are doing it in Kotlin. Still, coming from having done quite a bit of Scala there is something about Optionals that I’ve grown to like.

Now, I wanted to chain operations, calling the next method if the first didn’t yield something. With null/undefined values you’d use || in Javascript, so that’s why I introduced an or method in my Optional library. The result can be seen in Code of the Day.

Code of the Day

const transpose =
findTranspose(this.p1, direction, other)
.or(() => findTranspose(this.p2, direction, other))
.or(() => findTranspose(other.p1, direction, this))
.or(() => findTranspose(other.p2, direction, this))
.get();

return this.transpose(transpose.x, transpose.y);