复杂逻辑判断的写法笔记

134 阅读2分钟

1. 简单判断 且 返回是简单值

可以通过短路取值或者三目运算来解决

const status = a || b // 类同 a && b 需写清楚注释
const isTrue = a ? true : false;

2. 简单判断 且 判断之后需要做一些操作

最典型的莫过于 if else。但是这里有一些建议,就是结果尽早返回

if (a === 1) {
  // do something
} else if (b === 2) {
  // do something
} else {
  // do something
}

image.png

还有一种常用的 switch case。加入执行逻辑差不多的话,可以通过不加break进行穿透。

switch (params) {
  case 1:
  case 2:
    break;
  default: 
    // code
}

image.png

3. 复杂判断 且 判断之后需要做一些操作

Object

switch case 的这张图,可以联想到对象的键值对。

const strategies = {
  case1: function(a, b) {
    return a + b;
  },
  case2: function(a, b) {
    return a - b;
  },
  case3: function(a, b) {
    return a * b;
  },
  case4: function(a, b) {
    return a / b;
  }
}

function fn(key, a, b) {
  return strategies[key](a, b)
}

// 还能用字符串拼接的方式串联多个判断条件
function fn2(key, status) {
  return strategies[`${key}${status}`](a, b) || fn2.default()
}

image.png

Map

其实 Object 已经够用了,但是有些场景较为复杂,而 Objectkey 只能是字符串,所以在这种情况下就需要我们用 Map 作为容器,这样就可以用 对象和数组作为 Key。

const strategies = new Map([
  [{ code: 'case', status: 1 }, (a, b) => a + b],
  [{ code: 'case', status: 2 }, (a, b) => a - b],
  [{ code: 'case', status: 3 }, (a, b) => a * b],
  [{ code: 'case', status: 4 }, (a, b) => a / b],
  [{ code: 'default' }, () => console.log('没有该方法')],
])

const fn = (code, status) => {
  let action = [...strategies].find(([key]) => (key.code == code && key.status == status))
  return (...args) => action[1](...args)
}

fn('case', 1)(1, 2)

策略模式

  1. 将业务逻辑拆分(解耦),控制代码的复杂度。
  2. 添加新策略的时候,可以最小化改动。只要新增一个策略就可以解决问题。
interface Strategy {
  authenticate(...args: any): any;
}

class Authenticator {
  private strategy: Strategy;

  constructor(strategy: Strategy) {
    this.strategy = strategy;
  }

  // 设置/切换策略
  public setStrategy(strategy: Strategy) {
    this.strategy = strategy;
  }

  // 执行相应的策略逻辑
  public authenticate(...args: any): any {
    if (!this.strategy) {
      console.log('尚未设置认证策略');
      return;
    }
    return this.strategy.authenticate(...args);
  }
}

class WechatStrategy implements Strategy {
  authenticate(wechatToken: string) {
    if (wechatToken !== 'xxx') {
      console.log('无效的微信用户');
      return;
    }
    console.log('微信认证成功');
  }
}

class LocalStrategy implements Strategy {
  authenticate(username: string, password: string) {
    if (username !== 'xxx' && password !== 'xxx') {
      console.log('账号或密码错误');
      return;
    }
    console.log('账号和密码认证成功');
  }
}

const auth = new Authenticator(new WechatStrategy());
auth.authenticate('xxx');

auth.setStrategy(new LocalStrategy());
auth.authenticate('xxx', 'xxx');

参考资料