Home > Software design >  Typescript - Shorten code that has repetitive if expressions
Typescript - Shorten code that has repetitive if expressions

Time:11-01

I want to shorten my code that currently looks like this:

            onClick={value => {
        
          if (value === "valA") {
            Mutation.mutate({filter, source: "sourceA" }, {someRepetitiveCode}}, 
          } else if (value === "valB") {
            Mutation.mutate({filter, source: "sourceB" }, {someRepetitiveCode}}, 
         else {
            Mutation.mutate({filter, source: undefined },{someRepetitiveCode}} 
            
        }

There is a lot of repetition in the code so I wanted to ask if there is a way to shorten that expression.

CodePudding user response:

Your code is fine, no real need to shorten it, but here is an attempt...

 let source = undefined
 if (value === "valA") {
      source = "SourceA"
 } else if (value === "valB") {
      source = "SourceB"
 }
 Mutation.mutate({filter, source},{someRepetitiveCode}} 

CodePudding user response:

<button onClick={value => {
  const source = ({
    valA: 'sourceA',
    valB: 'sourceB',
  })[value];

  Mutation.mutate({ filter, source }, {someRepetitiveCode})
}}>
</button>

OR

<button onClick={value => {
  const source = (() => {
    switch (value) {
      case 'valA': return 'sourceA'
      case 'valB': return 'sourceB'
      default: return undefined // if value is not matching to any case
    }
  })();

  Mutation.mutate({ filter, source }, {someRepetitiveCode})
}}>
</button>

OR

<button onClick={value => {
  const source = (() => {
    if (value === 'valA') return 'sourceA'
    if (value === 'valB') return 'sourceB'
    return undefined // if any of condition matches
  })();

  Mutation.mutate({ filter, source }, {someRepetitiveCode})
}}>
</button>

Choose what you want. Each three ways have different pros/cons.

First one (getting from unnamed object literal) is shortest, but it can't handle complex situation

Second one (switch and return from IIFE) is little longer than the first one. but you can make it to get specific value instead of undefined when there's no matching condition.

Third one (if and return in IIFE) is longer than the second one and there's still few repeatations. But you can handle any case of complex situation.

  • Related