JavaScript 条件逻辑优化全指南

# JavaScript 条件逻辑优化全指南

一、基础优化方案

1. 对象字面量映射

// 优化前
function getStatusText(status) {
  if (status === 'success') return '成功';
  if (status === 'fail') return '失败';
  if (status === 'pending') return '进行中';
  return '未知状态';
}

// 优化后
const statusMap = {
  success: '成功',
  fail: '失败',
  pending: '进行中'
};

function getStatusText(status) {
  return statusMap[status] || '未知状态';
}

### 2. Map 数据结构
```javascript
// 更专业的键值映射
const errorMap = new Map([
  [400, '请求错误'],
  [401, '未授权'],
  [403, '禁止访问']
]);

function getErrorText(code) {
  return errorMap.get(code) || '未知错误';
}

二、高级策略模式

1. 完整策略模式实现

// 定义策略集
const strategies = {
  vip: (amount) => amount * 0.7,
  regular: (amount) => amount * 0.9,
  newcomer: (amount) => amount * 0.8,
  default: (amount) => amount
};

// 策略执行器
function calculatePrice(userType, amount) {
  const strategy = strategies[userType] || strategies.default;
  return strategy(amount);
}

// 使用示例
console.log(calculatePrice('vip', 100)); // 70

2. 策略模式 + 责任链

class DiscountChain {
  constructor() {
    this.rules = [
      { match: (type) => type === 'vip', apply: (amt) => amt * 0.7 },
      { match: (type) => type === 'coupon', apply: (amt) => amt * 0.9 },
      { match: () => true, apply: (amt) => amt } // 默认规则
    ];
  }

  calculate(type, amount) {
    const rule = this.rules.find(r => r.match(type));
    return rule.apply(amount);
  }
}

三、函数式编程方案

1. 高阶函数

const makeConditionalFn = (conditions) => (input) => {
  const matched = conditions.find(([predicate]) => predicate(input));
  return matched ? matched[1](input) : null;
};

const userTypeHandler = makeConditionalFn([
  [(type) => type === 'admin', () => '管理员'],
  [(type) => type === 'user', () => '普通用户']
]);

console.log(userTypeHandler('admin')); // "管理员"

2. 模式匹配提案

// 使用 @babel/plugin-proposal-pattern-matching
import { match } from 'pattern-matching';

const getAnimalSound = (animal) => match(animal)({
  'dog': () => 'woof',
  'cat': () => 'meow',
  _: () => 'unknown'
});

四、多条件复合判断优化

1. 条件表驱动

const rules = [
  {
    condition: (user) => user.age > 18 && user.score > 90,
    action: () => 'A级'
  },
  {
    condition: (user) => user.age > 18 && user.score > 60,
    action: () => 'B级'
  }
];

function evaluateUser(user) {
  const matchedRule = rules.find(rule => rule.condition(user));
  return matchedRule ? matchedRule.action() : 'C级';
}

2. 位运算优化

const PERMISSIONS = {
  READ: 1 << 0,    // 1
  WRITE: 1 << 1,   // 2
  DELETE: 1 << 2   // 4
};

function checkPermission(user, requiredPermission) {
  return (user.permissions & requiredPermission) === requiredPermission;
}

五、工程化解决方案

1. 配置化条件管理

// conditions.json
{
  "discount_rules": [
    {
      "type": "seasonal",
      "period": ["2023-12-01", "2023-12-31"],
      "rate": 0.8
    }
  ]
}

// 运行时加载
import rules from './conditions.json';

function applyDiscount(order) {
  const rule = rules.discount_rules.find(r => 
    order.type === r.type && 
    isDateInRange(order.date, r.period)
  );
  return rule ? order.amount * rule.rate : order.amount;
}

2. 规则引擎集成

// 使用 json-rules-engine
const { Engine } = require('json-rules-engine');

const engine = new Engine();
engine.addRule({
  conditions: {
    all: [{
      fact: 'user',
      operator: 'greaterThan',
      value: 18
    }]
  },
  event: { type: 'adult' }
});

六、性能对比

方法 可读性 可维护性 性能 适用场景
if-else 简单条件
switch-case 离散值匹配
对象映射 简单键值对应
策略模式 复杂业务规则
函数式条件处理 需要组合的条件逻辑
规则引擎 极高 频繁变更的复杂业务规则

七、最佳实践建议

  1. 简单条件:优先使用对象映射或Map
  2. 业务规则:采用策略模式
  3. 动态规则:考虑配置化或规则引擎
  4. 类型判断:使用多态或模式匹配
  5. 复合条件:使用责任链模式
// 终极优化示例
const createConditionEvaluator = (rules) => (input) => 
  rules.reduce((result, [predicate, action]) => 
    result ?? (predicate(input) ? action(input) : null), null);

const userLevelEvaluator = createConditionEvaluator([
  [(user) => user.vip, () => 'VIP用户'],
  [(user) => user.score > 100, () => '高级用户']
]);

记住:没有最好的方案,只有最适合的方案。根据项目的规模、团队习惯和性能要求选择合适的方法!

你可能感兴趣的:(WebAPIs,JavaScript,系列文章,JavaScript,javascript,开发语言,ecmascript)