const someFailedAction = (caseIds, growlMessages) => {
if (caseIds.length > 1) {
toastr.error(growlMessages[0], errorToastrOptions);
} else if (isCaseDetailsDisplayed) {
toastr.error(growlMessages[1], errorToastrOptions);
} else if (errorParts.fieldIds.length === 0) {
toastr.error(growlMessages[2], errorToastrOptions);
} else {
toastr.error(growlMessages[3], errorToastrOptions);
}
}
我有一堆像上面那样的条件语句,它们是针对不同案例操作的失败执行的。大多数动作都有相同的if / elseIf结构,但有些动作有一个额外的elseIf或一个或多个减法。
const SomeOtherFailedAction = (caseIds, growlMessages) => {
if (caseIds.length > 1) {
toastr.error(growlMessages[0], errorToastrOptions);
} else if (isCaseDetailsDisplayed) {
toastr.error(growlMessages[1], errorToastrOptions);
} else {
toastr.error(growlMessages[2], errorToastrOptions);
}
}
我想知道是否有一个好的设计模式,我可以直接传入消息的类型和数组,而不需要长的,嵌套的,重复的switch语句。
答案 0 :(得分:4)
只需使用布尔数组并找到成功的索引:
const i = [
caseIds.length > 1,
isCaseDetailsDisplayed,
errorParts.fieldIds.length === 0,
true
].indexOf(true);
toastr.error(growlMessages[i], errorToastrOptions)
或者,你可以存储一个可重复使用的函数数组,一个接一个地执行并返回函数返回true的第一个索引:
const tests = [
() => caseIds.length > 1,
() => isCaseDetailsDisplayed,
() => errorParts.fieldIds.length === 0,
() => true
]
const i = tests.findIndex(f => f());
toastr.error(growlMessages[i], errorToastrOptions)
答案 1 :(得分:3)
Jonas解决方案非常有效。请注意,您可以通过设置默认索引来干掉您拥有的内容,并仅在条件中覆盖它。然后在最后调用你的函数
const someFailedAction = (caseIds, growlMessages) => {
let idx = 3// replaces final `else` and is default
if (caseIds.length > 1) {
idx=0;
} else if (isCaseDetailsDisplayed) {
idx = 1;
} else if (errorParts.fieldIds.length === 0) {
idx= 2;
}// last `else` removed since already have a default
toastr.error(growlMessages[idx], errorToastrOptions);
}