6
[Code] Ternary-based pattern matching in JS - KaKi's blog
blog.kaki87.net# Ternary-based pattern matching in JS Folks are jealous of other programming
languages having this kind of pattern matching abilities : kotlin fun
compareNumbers( a: Int, b: Int ) = when { a > b -> "A is greater than B" b > a
-> "B is greater than A" else -> "A and B are equal" } But, so do we :
typescript const compareNumbers = ( a: number, b: number ) => a > b ? 'A is
greater than B' : b > a ? 'B is greater than A' : 'A and B are equal'; And this
example is at identical character count btw. For example, I use it here
[https://git.kaki87.net/KaKi87/dynapt/src/commit/9c89046de317295d7cd2e20e96b1a877a7ccfc72/src/updatePackages.js#L42-L44]
in dynapt(1) : javascript url = app.url ? app.url : app.github ?
`https://api.github.com/repos/$%7Bapp.github.repo%7D/releases/latest` :
undefined To define an app download url that is either already provided if
arbitrary, or requires being generated if from a GitHub / string. I
use it again in the same file a little lower
[https://git.kaki87.net/KaKi87/dynapt/src/commit/9c89046de317295d7cd2e20e96b1a877a7ccfc72/src/updatePackages.js#L64-L66]
: javascript isUnmodified = app.url ? response.status === 304 : app.github ?
response.status === 304 || cache[app.id]?.id === response.data['id'] :
undefined; To determine whethere the download file from the abovementioned URL
is modified or not, which works a little differently for GitHub because of its
API. In another project that uses Discord.JS and TypeScript, I use this syntax
for a conditional return type : typescript createSelectRow = ({ type // ... }: { type: type, // ... })
: type extends 'channel' ? ActionRowBuilder : type
extends 'role' ? ActionRowBuilder : type extends 'user' ?
ActionRowBuilder :
ActionRowBuilder => { // ... } Etc. — (1) dynapt is a
dynamic APT repository. More information about that project here
[https://gist.github.com/KaKi87/f620788e9901abbfef4978eb7ad358b4].
This is probably just my general dislike of chained ternary operators, but why not just write this out the “long” way to make intention clearer?
Probably just my general dislike of verbosity 😅
Yeh, I’d just do early return.
It’s not much more typing, and I find it easier to read and navigate specific conditional paths.
Some built in pattern matching would be cool (like the when keyword), but I’m not going to force it into my code