gpt4 book ai didi

javascript - 重构复杂的多条件 if-else 语句

转载 作者:行者123 更新时间:2023-11-28 12:12:01 24 4
gpt4 key购买 nike

所以基本上我创建了这个怪物,它检查用户是否选择了任何过滤器选项(用户也可以选择多个过滤器选项),将它们与数组中的值进行比较并返回过滤值的数组。它可以工作,但是将来维护它会变得更加困难,所以有什么办法可以将它分成模块并使其更加动态吗?

response = response.filter(job => {
const filterCategory = job.category.id === category;
const filterCountry = job.mainLocation.address.country === country;
const filterZip = job.mainLocation.address.zipCode === zip;
const filterName = findRightName(job, locale) === name;

if (name && country && zip && category) {
return filterCategory && filterCountry && filterZip && filterName;
} else if (name && country && zip) {
return filterCountry && filterZip && filterName;
} else if (name && country && category) {
return filterCategory && filterCountry && filterName;
} else if (name && zip && category) {
return filterCategory && filterZip && filterName;
} else if (country && zip && category) {
return filterCategory && filterCountry && filterZip;
} else if (name && country) {
return filterCountry && filterName;
} else if (name && category) {
return filterCategory && filterName;
} else if (name && zip) {
return filterZip && filterName;
} else if (zip && category) {
return filterCategory && filterZip;
} else if (country && zip) {
return filterCountry && filterZip;
} else if (country && category) {
return filterCategory && filterCountry;
} else if (name) {
return filterName;
} else if (country) {
return filterCountry;
} else if (zip) {
return filterZip;
} else if (category) {
return filterCategory;
} else {
return job;
}
});

最佳答案

您错过了您想要实现的目标的实际情况。而不是:

const filter = job.param === param;

你真正想要的只是在参数存在时失败。所以更好的表达方式是:

const filter = true;
if (param) filter = job.param === param;

或者用三元表达式:

const filter = param ? job.param === param : true;

使用此逻辑,您可以完全删除 if/else:

const filterCategory = category ? job.category.id === category                 : true;
const filterCountry = country ? job.mainLocation.address.country === country : true;
const filterZip = zip ? job.mainLocation.address.zipCode === zip : true;
const filterName = name ? findRightName(job, locale) === name : true;

return filterCategory && filterCountry && filterZip && filterName;

关于javascript - 重构复杂的多条件 if-else 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59968311/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com