实际开发中,有时会遇到多个条件语句杂糅到一起的情况,这时候如果使用多个 if...else... 语句嵌套,会使得代码的冗余程度大大增加。针对这种情况,可以做一些针对性的优化,来增加代码的可维护性。
单个条件
// beforeif (condition) {foo()}// aftercondition && foo()
if/else
if/else 通常可以使用两种优化策略:
- 排非策略
- 三元运算符
排非策略
排非即先对输入参数进行检查,若不符合条件的直接返回。if (!user || !password) return throw('用户名和密码不可为空🙅')// 后续逻辑处理
三元运算符
const allow = age >= 18 ? 'pass' : 'fail'condition ? success() : fail()
单个 if 多个条件
```typescript // before function foo(type) { if (type === ‘jpg’ || type === ‘png’ || type === ‘gif’) { consoel.log(‘something’) } }
// after function bar(type) { const types = [‘jpg’, ‘png’, ‘gif’] if (types.includes(type)) { console.log(‘something’) } }
<a name="O469T"></a>## 多个 else if 分支<a name="weM1Y"></a>### switch```typescriptswitch(val) {case 'A':handleA()breakcase 'B':handleB()break// ...}
k/v 优化
const enums = {'A': handleA,'B': handleB// ...}function action(val) {const handleType = enums[val]handleType()}
map 优化
const enums = new Map([['A', handleA],['B', handleB]// ...])function action(val) {const handleType = enums.get(val)handleType()}
// 组合使用let enums = new Map([['kline_A', handleKlineA],['kline_B', handleKlineB],['kline_C', handleKlineC],['kline_D', handleKlineD],['kline_E', handleKlineE],['depth_A', handleDepthA],['depth_B', handleDepthB],['depth_C', handleDepthC],])function action(mode, type){let key = `${mode}_${type}`let handleType = enums.get(key)handleType()}
