if else 嵌套優(yōu)化
function Demo (a, b, c) {
if (func1(a, b, c)) {
action ((a, b, c)=>{
// do something...
})
} else if (func2(a, b, c)) {
// do something...
action ((a, b, c)=>{
// do something...
})
}else if (func3(a, b, c)) {
action ((a, b, c)=>{
// do something...
})
}
}
func1(a,b,c){ do something}
func2(a,b,c){ do something}
func3(a,b,c){ do something}
各個分支控制下的代碼如下:
優(yōu)化后
const RuleMap = [
{
rule: func1(a, b, c) { do something //判斷是否匹配// },
action :function (a, b, c) {do something...}
},
{
rule: func2(a, b, c) { do something },
action :function (a, b, c) {do something...}
},
{
rule: func3(a, b, c) { do something },
action :function (a, b, c) {do something...}
}
]
function Control (a, b, c) {
for (let i = 0; i < RuleMap.length; i++) {
if (RuleMap[i].rule(a, b, c)) {
return RuleMap[i].action(a, b, c)
}
}
}
RuleMap是所有判斷規(guī)則和其執(zhí)行方法的合集毕源,RuleMap 中的每一項都具有 rule(規(guī)則) 與 action (方法)屬性畜普。這時可以將原有函數(shù)的 else if 改寫對職責(zé)鏈數(shù)組的遍歷株婴。這時每個rule一旦匹配,函數(shù)就會直接返回宏胯,通過此方法可以實現(xiàn)對單體復(fù)雜 else if 邏輯的拆分渔嚷。