DEV Community

Discussion on: ✔||🤢 Commit or Vomit | nested ternary operator

Collapse
 
idanarye profile image
Idan Arye

How is this formatting better than the original? The original is organized like a table, where the first column is the variable that accepts the result (only has a value in the first row, but that's fine), the second is the condition (which is empty for the last row, meaning "no condition - if all previous conditions were false) and the last is value.

This formatting, on the other hand, provides no hints regarding the role of each expression - they all start in the same column. Initially it may look like lines starting with ? are conditions and lines starting with : are result expressions, but this is not true for the last line. And yes, this is a property of the language's syntax, not the formatting, but OP's formatting was able to solve this with the tabular design and when the prettier flattened everything that hint was lost.

In this regard, I prefer Python's conditional operator. Manually formatted it looks better than OP's formatting of C conditionals, because I don't need to put lots of space before the last, condition-less result expression:

H = None if C == 0 else \
    (g - b) / C if V == r else \
    (b - r) / C + 2 if V == g else \
    (r - g) / C + 4
Enter fullscreen mode Exit fullscreen mode

But even if I prettify it with Black I get this:

H = (
    None
    if C == 0
    else (g - b) / C
    if V == r
    else (b - r) / C + 2
    if V == g
    else (r - g) / C + 4
)
Enter fullscreen mode Exit fullscreen mode

And yes - just like your prettified C code it is flat, but at least here, thanks to the language's syntax, the structure is clear - all lines starting with if are conditions and all lines starting with else are result expressions - so it's still readable.

Collapse
 
lexlohr profile image
Alex Lohr

It's JS, not C, and the secret to reading it is in the rythm:

Q1
? Y1
: N1/Q2
? Y2
: N2;
Enter fullscreen mode Exit fullscreen mode

Once you're used to the pattern, it is more legible than the other version.

That being said, I really like the verbose ternary of Python and Rust. Unfortunately they'll never be supported by ECMAscript.

Thread Thread
 
idanarye profile image
Idan Arye

Rust is a different story. It's not a ternary conditional operator there - it's a full blown if expression and any prettifier would format it with proper indentations:

let H = if C == 0 {
    None
} else if V == r {
    Some((g - b) / C)
} else if V == g {
    Some((b - r) / C + 2)
} else {
    Some((r - g) / C + 4)
};
Enter fullscreen mode Exit fullscreen mode