打字稿中开关的替代品
我正在尝试为我的开关柜考虑任何替代方案,因为它很长我有嵌套的开关盒,看起来像这样
I am trying to think of any alternative for my switchcase as it is a very long I have nested switch case which looks like this
switch (currentTab) {
case pending:
switch (status) {
case approved:
case denied:
break;
case partialApproved:
finalUpdatedInvoiceAmount = updatedInvoiceAmount - (feeAmount - (approvedFeeAmount || 0));
break;
}
break;
case approved:
switch (status) {
case denied:
case partialApproved:
finalUpdatedInvoiceAmount = updatedInvoiceAmount - (feeAmount - (approvedFeeAmount || 0));
break;
}
break;
case denied:
switch (status) {
case approved:
case partialApproved:
finalUpdatedInvoiceAmount = oldApprovedFeeAmount ? updatedInvoiceAmount + (feeAmount - oldApprovedFeeAmount) : updatedInvoiceAmount - (feeAmount - (approvedFeeAmount || 0));
break;
}
break;
case partiallyApprovedTab:
switch (status) {
case approved:
case denied:
case partialApproved:
finalUpdatedInvoiceAmount = oldApprovedFeeAmount ? updatedInvoiceAmount + (feeAmount - oldApprovedFeeAmount) : updatedInvoiceAmount - (feeAmount - (approvedFeeAmount || 0));
break;
}
break;
}
这是另一种可能性吗?由于代码非常庞大,以后可能会进入其他情况.
is an alternate possibility for this? As the code is very huge and later other cases might enter in this.
推荐答案
或许你可以试试handlerMap:
Maybe you can try handlerMap:
const handler1 = () => { finalUpdatedInvoiceAmount = updatedInvoiceAmount - (feeAmount - (approvedFeeAmount || 0)); }
const handler2 = () => { finalUpdatedInvoiceAmount = oldApprovedFeeAmount ? updatedInvoiceAmount + (feeAmount - oldApprovedFeeAmount) : updatedInvoiceAmount - (feeAmount - (approvedFeeAmount || 0)); }
const handlerMap = {
[pending]: {
[partialApproved]: handler1
},
[approved]: {
[denied]: handler1,
[partialApproved]: handler1,
},
[denied]: {
[approved]: handler2,
[partialApproved]: handler2,
},
[partiallyApprovedTab]: {
[approved]: handler2,
[denied]: handler2,
[partialApproved]: handler2,
}
}
handlerMap[currentTab] && handlerMap[currentTab][status] && handlerMap[currentTab][status]()
// handlerMap[currentTab]?.[status]?.()
相关文章