重构嵌套的 If-Else 语句
Refactoring Nested If-Else Statements
你能帮我提供一些关于如何重构以下嵌套 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);
}
一旦我引入更多的年龄和身高类别,它就会变得非常难看。有没有可能缩短代码并使其更漂亮? switch 语句是有问题的,因为第二个变量是一个整数。
对于价格随年龄和身高而变化的一般情况,请从按年龄索引的对象开始。在内部,对于每个年龄段,您可以有一系列身高阈值及其相关价格。 .find
数组中的第一个匹配阈值给定高度,return 相关价格。
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];
}
你能帮我提供一些关于如何重构以下嵌套 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);
}
一旦我引入更多的年龄和身高类别,它就会变得非常难看。有没有可能缩短代码并使其更漂亮? switch 语句是有问题的,因为第二个变量是一个整数。
对于价格随年龄和身高而变化的一般情况,请从按年龄索引的对象开始。在内部,对于每个年龄段,您可以有一系列身高阈值及其相关价格。 .find
数组中的第一个匹配阈值给定高度,return 相关价格。
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];
}