简体   繁体   中英

Deleting code duplication in JavaScript

I notice quite a lot of my code is duplicated purely because I do not know how to refactor it differently taking a variable into consideration.

This is the code inside my react render method:

          if (card.suit == 'D' || card.suit == 'H'){
            return <div className="cardFormatDH" key={ index }> {card.rankKey}{card.suit} </div>;
          }
          else if (card.suit == 'C' || card.suit == 'S'){
            return <div className="cardFormatCS" key={ index }> {card.rankKey}{card.suit} </div>;
          }

effectively what I would like to say is something like:

return exactly the same thing whether it is d/h or c/s, just allow c/s to have the same style and d/h to have the same style. also my if condition is quite long but I cant figure a way to shorten it down

You could create a suit -> className map:

const cls = {
  D: 'DH',
  H: 'DH',
  C: 'CS',
  S: 'CS',
};

and look up the suit in the table, using the value as part of the class name:

if (cls[card.suit]) {
  return <div className={`cardFormat${cls[card.suit]}`} key={ index }> {card.rankKey}{card.suit} </div>;
}

You could write a getCardClassname function:

function getCardClassname(suit) {
  if (card.suit == 'D' || card.suit == 'H'){
    return "cardFormatDH";
  }
  else if (card.suit == 'C' || card.suit == 'S'){
    return "cardFormatCS";
  }
}

return <div className={getCardClassname(card.suit)} key={ index }> {card.rankKey}{card.suit} </div>;
  // you can add more pairs here 
  const formats = [ ['D', 'H'], ['C', 'S'] ]; 

  for(let format of formats) {
    if(format.includes(card.suit)) {
      return (
        <div className=`cardFormat${format.join('')}` key={ index }> 
          {card.rankKey}{card.suit} 
        </div>
      );
    }
  } 

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