减少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
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值