Skip to content
Advertisement

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',
      }))
    )

Advertisement

Answer

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.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement