简体   繁体   English

重构嵌套的 If-Else 语句

[英]Refactoring Nested If-Else Statements

could you help me give me some ideas how to refactor the following nested if-statement?你能帮我给我一些想法如何重构以下嵌套的 if 语句吗?

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. Switch 语句有问题,因为第二个变量是 integer。

For the general case when the prices change for each age and height, start with an object indexed by age.对于每个年龄和身高的价格变化的一般情况,从按年龄索引的 object 开始。 Inside, for each age, you could have an array of height thresholds and their associated price.在内部,对于每个年龄,您都可以拥有一系列身高阈值及其相关价格。 .find in the array the first matching threshold given the height, and return the associated price. . 在.find中找到给定高度的第一个匹配阈值,并返回相关价格。

const config = {
    'under 18': [
        // [Height must be <= this, to get this price]
        [1.5, 6.18],
        [1.8, 5.59],
        [Infinity, 5.37]
    ],
    '18-50': [ // change as needed
        [1.5, 6.18],
        [1.8, 5.59],
        [Infinity, 5.37]
    ],
    // ...
}
function priceCalculator(age, height) {
    return config[age]
        .find(([threshold]) => height <= threshold)
        [1];
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM