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 = 6.18;
      } else if (height > 1.5 && height <= 1.8) {
          price = 5.59;
      } else if (height > 1.8) {
          price = 5.37;
      }
  } else if (age == "over 50") {
      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;
      }
  }

  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.

1 thought on “Refactoring Nested If-Else Statements”

Leave a Comment