Ternary-based pattern matching in JS

Folks are jealous of other programming languages having this kind of pattern matching abilities :

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 :

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 in dynapt(1) :

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 <owner>/<repo> string.

I use it again in the same file a little lower :

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 :

createSelectRow = <type extends 'channel' | 'role' | 'user' | 'string'>({
    type
    // ...
}: {
    type: type,
    // ...
}) : type extends 'channel' ? ActionRowBuilder<ChannelSelectMenuBuilder>
   : type extends 'role'    ? ActionRowBuilder<RoleSelectMenuBuilder>
   : type extends 'user'    ? ActionRowBuilder<UserSelectMenuBuilder>
                            : ActionRowBuilder<StringSelectMenuBuilder> =>
{
    // ...
}

Etc.


(1) dynapt is a dynamic APT repository. More information about that project here.