dimanche 31 janvier 2021

Refactoring Nested If-Else Statements

could you help me give me some ideas how to refactor the following nested if-statement?

function priceCalculator(age, height) {

  if (age == "under 18") {
      if (height <= 1.5) {
          price = 6.18;
      } else if (height > 1.5 && height <= 1.8) {
          price = 5.59;
      } else if (height > 1.8) {
          price = 5.37;
      }
  } else if (age == "18-50") {
      if (height <= 1.5) {
          price = 7.38;
      } else if (height > 1.5 && height <= 1.8) {
          price = 6.19;
      } else if (height > 1.8) {
          price = 7.22;
      }
  } else if (age == "over 50") {
      if (height <= 1.5) {
          price = 8.48;
      } else if (height > 1.5 && height <= 1.8) {
          price = 8.53;
      } else if (height > 1.8) {
          price = 8.17;
      }
  }

  console.log(price);
}

It gets pretty ugly, once I introduce even more age and height categories. Is there a possibility to kind of shorten the code and make it prettier? Switch statements are problematic, because the second variable is an integer.

Aucun commentaire:

Enregistrer un commentaire