我有一个函数,该函数根据类型选项返回有效载荷的对象(可以为'0','1'或'2')。将多个if语句重构为更可重用/功能更好的方法是什么?
const getPayload = type => {
if (type === '0') {
return {
amount: current_amount || amount,
type: 'TYPE_TEST1',
}
}
if (type === '1') {
return {
percent: current_amount || amount,
type: 'TYPE_TEST2',
}
}
if (type === '2') {
return {
percent: current_amount || amount,
type: 'TYPE_TEST3',
}
}
}
答案 0 :(得分:3)
您可以使用对象将类型与值映射,然后只需返回所获得的任何类型的值即可。
var types = {
0: {
amount: current_amount || amount,
type: 'TYPE_TEST1',
},
1: {
percent: current_amount || amount,
type: 'TYPE_TEST2',
},
2: {
percent: current_amount || amount,
type: 'TYPE_TEST3',
}
}
function getType(type) {
return types[type];
}