3 ms·
Ironically, it could have been written far more concisely and clearly by using IIFE, if-then statements and reordering the logic: const result = (() => {
by ravenstine 7y ago
Ironically, it could have been written far more concisely and clearly by using IIFE, if-then statements and reordering the logic:
const result = (() => {
if (!conditionA) return 'Not A';
if (conditionB) return 'A & B';
return 'A';
})();
Yes, I know, I "need" to use curlies. But there's really no reason why someone shouldn't be able to quickly make sense of this. The ternary, on the other hand, is unnecessarily cryptic.
- correct_horse 7y agoCan't help but call out Rust here for it's (imo excellent) syntax. if condition {do_x()} else {do_y()} Basically there's no need for line breaks between if/else, but also they decided not to add a ternary conditional operator.
- ravenstine 7y agoif (condition) { do_x() } else { do_y() } That's the JavaScript version of what you wrote, and it's nearly identical. JavaScript doesn't require line breaks.
- kbp 7y agoThe significant difference is that in Rust, like in Lisp, `if` is an expression, so if-else essentially is the ternary operator. const x = cond1 ? a : cond2 ? b : c becomes in Rust let x = if cond1 { a } else if cond2 { b } else { c }
- tobr 7y agoWhether that’s clearer or not should be a matter of debate. I find the introduction of a function for this a potential source of confusion, when it just serves to turn statements into an expression. But it’s not an unreasonable solution. However, I’m not sure how this is supposed to be “written far more concisely”? It’s more verbose, involves more different constructs, more levels of indirection - pretty much for any definition of “conciseness“ I can think of, it is worse.