Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I avoid nested ternary expressions in my code?

I have code like this. How can I write it in cleaner, more elegant way using functional programming in JavaScript? I want to get rid of nested ternary expressions. Any ideas?

props => ({
            iconColor: props.isPriority ? (props.isCompleted ? variables.color.lightpurple : variables.color.purple ) : variables.color.gray3,
            iconName: props.isPriority ? 'star-full' : 'star-empty',
          }))

This is rest of that code:

EDIT:

const enhance: React$HOC<*, InitialProps> = compose(
      withProps(props => ({
        iconColor: props.isPriority ? (props.isCompleted ? variables.color.lightpurple : variables.color.purple) : variables.color.gray3,
        iconName: props.isPriority ? 'star-full' : 'star-empty',
      }))
    )
like image 560
MountainConqueror Avatar asked Sep 18 '17 05:09

MountainConqueror


People also ask

How do I stop nested ternary operators?

Use an ESLint rule If you use ESLint in your project, you can use this rule to disallow nested ternary expressions.

What can I use instead of a ternary operator?

The alternative to the ternary operation is to use the && (AND) operation. Because the AND operator will short-circuit if the left-operand is falsey, it acts identically to the first part of the ternary operator.

Why we should not use ternary operator?

They simply are. They very easily allow for very sloppy and difficult to maintain code. Very sloppy and difficult to maintain code is bad. Therefore a lot of people improperly assume (since it's all they've ever seen come from them) that ternary operators are bad.


1 Answers

Yes, but my linter is not happy: 44:16 error Do not nest ternary expressions [no-nested-ternary]

If that's your only problem then the solution is simple. Create your own conditional function:

const iff = (condition, then, otherwise) => condition ? then : otherwise;

props => ({
  iconColor: props.isPriority ?
    iff(props.isCompleted, variables.color.lightpurple, variables.color.purple) :
    variables.color.gray3,
  iconName: props.isPriority ? 'star-full' : 'star-empty',
})

Now your linter shouldn't complain. That being said, you should disable [no-nested-ternary] in your linter. It's kind of stupid that your linter thinks that nested conditionals are bad.

like image 54
Aadit M Shah Avatar answered Sep 20 '22 02:09

Aadit M Shah