这段 if...else 有优雅的写法吗?

查看 334|回复 22
Kakaaa   

xiangyuecn   
var order="xxx",prop="rate"
var sortType=(
/**/ ({descending:
/*----*/ {thisYearIncome:1,lastYearIncome:3,rate:5}
/**/ })[order] ||
/*----*/ {thisYearIncome:2,lastYearIncome:4,rate:6}
)[prop]||0;
davin   
先定义枚举吧,不然时间久了怎么解释这些 1 到 6
···
enum SortType {
THIS_YEAR_INCOME_DESC = 1,
THIS_YEAR_INCOME_ASC = 2,
LAST_YEAR_INCOME_DESC = 3,
LAST_YEAR_INCOME_ASC = 4,
RATE_DESC = 5,
RATE_ASC = 6
}
···
yangg   
接口设计有问题,搞什么 1 ,2,3 ,4,5,6 的参数
bertonzh   
{
'descending-thisYearIncome': 1,
'descending-lastYearIncome': 3,
}[`${order}-${prop}`]
MorJS   
function onSortChange({ order, prop }) {
const sortMap = {
'descending': { 'thisYearIncome': 1, 'lastYearIncome': 3, 'rate': 5 },
'ascending': { 'thisYearIncome': 2, 'lastYearIncome': 4, 'rate': 6 }
};
const sortType = sortMap[order]?.[prop] || 0;
this.fetchData(sortType);
}
yuzo555   
function onSortChange({ order, prop }) {
const sortTypes = {
thisYearIncome: order === 'descending' ? 1 : 2,
lastYearIncome: order === 'descending' ? 3 : 4,
rate: order === 'descending' ? 5 : 6,
};
this.fetchData(sortTypes[prop] || 0);
}
foolnius   
const defineObject = {
descending_thisYearIncome: 1, //注释
thisYearIncome: 3, //注释
descending_lastYearIncome: 3, //注释
lastYearIncome: 4, //注释
descending_rate: 5, //注释
rate: 6, //注释
};
function onSortChange({ order, prop }) {
const key = `${order === "descending" ? `${order}_` : ""}${prop}`;
this.fetchData(defineObject[key] ?? 0);
}
NessajCN   
function onSortChange({ order, prop }) {
const l=["thisYearIncome", "lastYearIncome", "rate"];
const sortType = order === "descending" ? l.indexOf(prop)*2+1 : l.indexOf(prop)*2+2;
this.fetchData(sortType)
}
wysnxzm   
switch 或者 map
各种设计模式最终也都是依赖 map 进行实现比如策略模式
您需要登录后才可以回帖 登录 | 立即注册

返回顶部