# JavaScript 条件逻辑优化全指南
// 优化前
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) || '未知错误';
}
// 定义策略集
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
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);
}
}
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')); // "管理员"
// 使用 @babel/plugin-proposal-pattern-matching
import { match } from 'pattern-matching';
const getAnimalSound = (animal) => match(animal)({
'dog': () => 'woof',
'cat': () => 'meow',
_: () => 'unknown'
});
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级';
}
const PERMISSIONS = {
READ: 1 << 0, // 1
WRITE: 1 << 1, // 2
DELETE: 1 << 2 // 4
};
function checkPermission(user, requiredPermission) {
return (user.permissions & requiredPermission) === requiredPermission;
}
// 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;
}
// 使用 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 | 中 | 中 | 高 | 离散值匹配 |
对象映射 | 高 | 高 | 高 | 简单键值对应 |
策略模式 | 高 | 高 | 中 | 复杂业务规则 |
函数式条件处理 | 高 | 高 | 中 | 需要组合的条件逻辑 |
规则引擎 | 高 | 极高 | 低 | 频繁变更的复杂业务规则 |
// 终极优化示例
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, () => '高级用户']
]);
记住:没有最好的方案,只有最适合的方案。根据项目的规模、团队习惯和性能要求选择合适的方法!