Home > Software engineering >  How can I improve this? using typescript
How can I improve this? using typescript

Time:11-06

const ProgressBarVertical: React.FC<ProgressProps> = ({
  Levelorder,
  currentLevel,
 }) => {
  if (Levelorder === 0) {
       switch (currentLevel) {
         case 0:
           return <View style={styles.progressIncompleteFirst} />
         default:
           return <View style={styles.progressCompleteFirst} />
       }
  } else if (Levelorder > currentLevel) {
     return <View style={styles.progressIncomplete} />
  } else if (Levelorder < currentLevel) {
     return <View style={styles.progressComplete} />
  } else {
     return <View style={styles.progressIncomplete} />
  }

I'm was in a rush and I did my conditions like this, But I feel I still can improve this. Can someone show me how?

CodePudding user response:

As with any refactoring look for things that repeat and try to make them not repeat. The first thing I notice is that you render a <View /> many times, just with a different style prop. So what if you rendered that once instead?

const ProgressBarVertical: React.FC<ProgressProps> = ({
  Levelorder,
  currentLevel,
}) => {
    return <View style={getStyle(Levelorder, currentLevel)} />
}

Now you can implement getStyle. Note that by using an early return you can keep the number of conditional curly braces down quite a bit.

function getStyle(Levelorder: number, currentLevel: number): ViewStyle {
    if (Levelorder === 0) {
        return currentLevel === 0 ?
            styles.progressIncompleteFirst :
            styles.progressCompleteFirst
    }

    if (Levelorder < currentLevel) return styles.progressComplete
    
    return styles.progressIncomplete
}

The first if handles the special case where Levelorder is zero. The second if handles the completed case, and then last just return the only other option (equal to or grater than) if neither of the previous two returns were executed.

  • Related