alternate ternary formatting
See original GitHub issueHere is how Prettier currently reformats nested ternaries:
const value = condition1
? value1
: condition2
? value2
: condition3
? value3
: value4;
This isn’t so bad when there are only two ternaries, but I sometimes have many more because I essentially use them as an alternative to a switch statement when each case only gets a single value.
Here is how I prefer to format this case:
const value =
condition1 ? value1 :
condition2 ? value2 :
condition3 ? value3 :
value4;
I like this because it clearly associates each condition with its corresponding value and the indentation doesn’t increase regardless of the number of ternaries.
Perhaps some like the current formatting because it discourages use of nested ternaries, but I think my example shows that you can have any number without making the code hard to read.
Would you consider adding an option to support this alternate formatting? Maybe something like this? --ternary=condval
Issue Analytics
- State:
- Created 7 years ago
- Reactions:51
- Comments:40 (18 by maintainers)
Ternary style is always controversial, personally I write them more like
if-elseif-else
chains:This keeps confusing people both inside and outside of Facebook. Here’s a proposal:
If there is a strict chain of ternaries, then write it the following way:
We need to make sure that the fully nested ones are expanded, otherwise it looks really weird.
This is not as good looking as
but at least it’s compatible with the current way we print ternaries and it doesn’t have issues when both don’t fit in a single line.
What do you think?