如何改进这个JS代码,使其看起来更优雅



在我的React应用程序中,我使用Material UI编写了一段代码来管理联系人表单的字段大小。这些字段是可以根据配置添加或删除的元素。

我写的代码工作正常,但看起来很难看,我需要帮助使它变得更好。

let size = 12;
if (useMediaQuery(theme.breakpoints.up('sm'))) {
const hasTime = fieldsConfig.some(
f => f.name === 'preferredContactHours',
);
const hasContactType = fieldsConfig.some(
f => f.name === 'preferredContactWay',
);
if (name === 'phone' && (!hasTime || !hasContactType)) size = 7;
else if (name === 'preferredContactWay' && hasTime) size = 6;
else if (name === 'preferredContactWay' && !hasTime) size = 5;
else if (name === 'preferredContactHours' && hasContactType) size = 6;
else if (name === 'preferredContactHours' && !hasContactType) size = 5;
}

默认情况下,大小为12,因此,如果任何条件不适用,则该字段在网格中仍将是完全大小。

字段hasTimehasContactType是可选的,所以我需要检查它们是否存在。

剩下的就是检查字段是否存在,并相应地设置大小。

如果可能的话,我需要的是让它比所有这些冗长的代码更好、更高效。

有很多方法可以提高代码的质量。这不是唯一的方法。我认为这可以使您的代码具有更高的内聚性和更少的耦合风格。希望这对你有帮助。

附言:我没有测试代码。

const sizeResult = document.querySelector('#size')
let size = 12

const name = 'preferredContactWay'
const fieldsConfig = [{ name: 'preferredContactHoursss' }]
const useMediaQuery = () => true
// Object size configuration. This helps to avoid `if`s.
const sizeConfiguration = {
preferredContactWay_true: 6,
preferredContactWay_false: 6,
preferredContactHours_true: 6,
preferredContactHours_false: 6,
phone: 7, 
}
/* SRP (Single Responsibility Principle). One of the SOLID principles and a good practice of  the Clean Architecture 
Each function must have only one reason to change (single responsibility)
*/
function getHasTimeValue() {
return fieldsConfig.some(
f => f.name === 'preferredContactHours',
)
}
function getHasContactTypeValue() {
return fieldsConfig.some(
f => f.name === 'preferredContactWay',
)
}
function getSize(_name) {
const param = getHasTimeValue() ? getHasTimeValue() : getHasContactTypeValue()
return param ? sizeConfiguration[`${_name}_${param}`] : sizeConfiguration['phone']
}
function Main() {
if (useMediaQuery()) {
size = getSize(name)
sizeResult.innerHTML = size
} 
}
Main()

sizeResult.innerHTML = size
<div id="size"></div>

相关内容

最新更新