简体   繁体   中英

Swap nested ternary expressions to cond using ramda.js

I have working code using nested ternary expressions. Is there any way to make it cleaner using ramda.js or another functional helper? Will cond be a good choice?

I'm new to ramda and I don't know exactly how to convert that piece of code to ramda way.

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

converting just that insane long line:

iconColor: props.isPriority ? (props.isCompleted ? variables.color.lightpurple : variables.color.purple ) : variables.color.gray3,

would be more than enougth.

R.cond is definitely one option for removing the nesting. This could also be combined with R.applySpec to produce an object whose values are all derived from the same argument ( props in your instance).

const enhance: React$HOC<*, InitialProps> = compose(withProps(R.applySpec({
    iconColor: R.cond([
        [({ isPriority }) => !isPriority, () => variables.color.gray3],
        [({ isCompleted }) => isCompleted, () => variables.color.lightpurple],
        [() => true, () => variables.color.purple]
    ]),
    iconName: ({ isPriority }) => isPriority ? 'star-full' : 'star-empty'
})))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM