if-else statement and duplicate ternery expressions refactored

If we have duplicate code like this:

const SeasonDisplay = (props) => {
  const season = getSeason(props.lat, new Date().getMonth());
  const seasonResponse =
    season === "winter" ? "Burr, it's chilly" : "Let's hit the beach";
  const iconName = season === "winter" ? "snowflake" : "sun";

  return (
    <div>
      <i className={`${iconName} icon`} />
      <h1>{seasonResponse}</h1>
      <i className={`${iconName} icon`} />
    </div>
  );
};

  

  return (
    <div>
      <i className={`${iconName} icon`} />
      <h1>{seasonResponse}</h1>
      <i className={`${iconName} icon`} />
    </div>
  );

it can be refactored into a if-else statement:

const SeasonDisplay = (props) => {

 let seasonResponse = "";
 let iconName = "";
  if (season === "winter") {
    seasonResponse = "Burr, it's chilly";
    iconName = "snowflake";
  } else {
    seasonResponse = "Let's hit the beach";
    iconName = "sun";
  }
  return (
    <div>
      <i className={`${iconName} icon`} />
      <h1>{seasonResponse}</h1>
      <i className={`${iconName} icon`} />
    </div>
  );
};

but even better would be to create a seasonConfig object!

const seasonConfig = {
  summer: {
    text: "Let's hit the beach!",
    iconName: "sun",
  },
  winter: {
    text: "Burr, it's chilly",
    iconName: "snowflake",
  },
};
const SeasonDisplay = (props) => {
  const season = getSeason(props.lat, new Date().getMonth());
  const { seasonResponse, iconName } = seasonConfig[season]; //seasonResponse, iconName
  return (
    <div>
      <i className={`${iconName} icon`} />
      <h1>{seasonResponse}</h1>
      <i className={`${iconName} icon`} />
    </div>
  );
};

Add your comment