这是我计算BMI (体重指数)的代码。
我怎样才能使这个代码更好呢?
const computeBMI = (weight, height, country) => {
const countries = ["Chad", "Sierra Leone", "Mali", "Gambia", "Uganda", "Ghana", "Senegal", "Somalia", "Ivory Coast", "Isreal"];
let heightInMeters = height * 0.3048;
let BMI = weight / (heightInMeters * heightInMeters);
for (let i = 0; i < countries.length; i++) {
if (countries[i] === country) {
const bmiTotal = BMI * 0.82;
return Math.round(bmiTotal, 2);
}
}
return Math.round(BMI, 2);
};发布于 2019-05-08 09:07:50
您的代码看起来已经很好了。然而,还有一些细节需要改进:
1)有Array.includes,它将抽象化for循环,使代码更加简洁。
2)使用bmiTotal和BMI,尽管两者的含义相同。
const countriesWithLowerBIP = ["Chad", "Sierra Leone", "Mali", "Gambia", "Uganda", "Ghana", "Senegal", "Somalia", "Ivory Coast", "Isreal"];
const computeBMI = (weight /*in kg*/, height /*in feet*/, country) => {
const heightInMeters = height * 0.3048;
let BMI = weight / (heightInMeters ** 2);
if (countriesWithLowerBIP.includes(country))
BMI *= 0.82;
return Math.round(BMI, 2);
};发布于 2019-05-08 15:58:46
避免神奇的数字。那是0.3048和0.82。当另一个开发人员进来查看代码时,他们将不知道这些数字是什么。将它们放入相应命名的变量中。
你把高度转换成米,这意味着height没有米。是哪个单位进来的?是其他公制单位还是另一个单位?你没有转换weight。weight已经在公制中了吗?最好用单位作为参数名。
此外,坚持一个单位的计算。把转换转移到别处。例如,用公制来写所有的东西。然后为其他单元创建单独的API,在那里执行到度量的转换,然后调用度量API。
这个循环是为特定国家调整BMI的一种长时间的方法。我花了一段时间才弄明白。如果能对整个块的功能添加注释,那就太好了。另外,还有array.includes()。
最后,函数中的任何常量值(从字面上说永远不变的值,如您的国家列表和比率),都应该退出该函数。使功能不那么杂乱。而且,您不希望每次调用函数时都重新创建这些值。
const adjustedRatio = 0.82
const countries = [...];
const computeBMI = (kilograms, meters, country) => {
const baseBMI = weight / (meters * meters);
const shouldRatio = countries.includes(country)
const modifiedBMI = shouldRatio ? baseBMI * adjustedRatio : baseBMI
return Math.round(modifiedBMI, 2);
};
// For non-metric users
const computeBMINonMetric = (pounds, feet, country) => {
// TODO: convert pounds to kilograms
// TODO: convert feet to meters
return computeBMI(kilograms, meters, country)
}发布于 2019-05-08 08:50:10
我就是这么做的。只有一部分,你可以削减一点,是使用for循环,以确定该人是否来自国家名单。在那里,可以使用countries.indexOf( country )返回数组中国家的索引,如果国家不在数组中,则使用-1。您可以在if子句中使用它。
否则对我来说很好。
https://codereview.stackexchange.com/questions/219920
复制相似问题