减少if-else的几个小技巧

减少if-else的几个小技巧

短路运算

使用前:

let c
if(a){
    
    
    c = a
} else {
    
    
    c = b
}

使用后:

let c = a || b

三元运算符

使用前

const fn = (nBoolean) {
    
    
    if (nBoolean) {
    
    
        return 1
    } else {
    
    
        return 0
    } 
}

使用后

const fn = (nBoolean) {
    
    
    return nBoolean ? 1 : 0
}

switch case

有A、B、C、D四种种类型,在A、B的时候输出1,C输出2、D输出3,默认输出0。

使用前

let type = 'A'

//if else if
if (type === 'A' || type === 'B') {
    
    
    console.log(1);
} else if (type === 'C') {
    
    
    console.log(2);
} else if(type === 'D') {
    
    
    console.log(3);
} else {
    
    
    console.log(0)
}

使用后

switch (type) {
    
    
    case 'A':
    case 'B':
        console.log(1)
        break
    case 'C':
        console.log(2)
        break
    case 'D':
        console.log(3);
        break;
    default:
        console.log(0)
}

对象配置/策略模式

let type = 'A'

let tactics = {
    
    
    'A': 1,
    'B': 1,
    'C': 2,
    'D': 3,
    default: 0
}
console.log(tactics[type]) // 1

实用案例

折扣

const getDiscount = (userKey) => {
    
    
    // 我们可以根据用户类型来生成我们的折扣对象
    let discounts = {
    
    
        '两件': 0.9,
        '三件': 0.8,
        '四件': 0.7,
        'default': 1
    }
    return discounts[userKey] || discounts['default']
    //  Map管理
    let discounts = new Map([
        ['两件', 0.9],
        ['三件', 0.8],
        ['四件', 0.7],
        ['default', 1]
    ])
    return discounts.get(userKey) || discounts.get('default')
}
console.log(getDiscount('两件')) // 0.9

年终奖

公司的年终奖根据员工的工资基数和绩效等级来发放的。例如,绩效为A的人年终奖有4倍工资,绩效为B的有3倍,绩效为C的只有2倍

let strategies = new Map([
    ['A', 4],
    ['B', 3],
    ['C', 2]
])
const calculateBonus = (performanceLevel, salary) => {
    
     
    return strategies.get(performanceLevel) * salary
}
calculateBonus( 'B', 20000 ) // 60000

假设公司有两个部门D和F,D部门的业绩较好,所以年终奖翻1.2倍,F部门的业绩较差,年终奖打9折

let strategies = new Map([
    ['A_D', 4 * 1.2],
    ['B_D', 3 * 1.2],
    ['C_D', 2 * 1.2],
    ['A_F', 4 * 0.9],
    ['B_F', 3 * 0.9],
    ['C_F', 2 * 0.9]
])
const calculateBonus = (performanceLevel, salary, department) => {
    
     
    return strategies.get(`${
      
      performanceLevel}_${
      
      department}`) * salary
}
calculateBonus( 'B', 20000, 'D' ) // 72000

猜你喜欢

转载自blog.csdn.net/MoXinXueWEB/article/details/129161738