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?
JavaScript
x
5
1
props => ({
2
iconColor: props.isPriority ? (props.isCompleted ? variables.color.lightpurple : variables.color.purple ) : variables.color.gray3,
3
iconName: props.isPriority ? 'star-full' : 'star-empty',
4
}))
5
This is rest of that code:
EDIT:
JavaScript
1
7
1
const enhance: React$HOC<*, InitialProps> = compose(
2
withProps(props => ({
3
iconColor: props.isPriority ? (props.isCompleted ? variables.color.lightpurple : variables.color.purple) : variables.color.gray3,
4
iconName: props.isPriority ? 'star-full' : 'star-empty',
5
}))
6
)
7
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:
JavaScript
1
9
1
const iff = (condition, then, otherwise) => condition ? then : otherwise;
2
3
props => ({
4
iconColor: props.isPriority ?
5
iff(props.isCompleted, variables.color.lightpurple, variables.color.purple) :
6
variables.color.gray3,
7
iconName: props.isPriority ? 'star-full' : 'star-empty',
8
})
9
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.