js中减少if-else的几个小技巧

225 篇文章 1 订阅
207 篇文章 4 订阅

1.使用三目运算符,这个很多朋友都用过的;

例子:条件为 true 时返回1,反之返回0const fn = (nBoolean) {
    if (nBoolean) {
        return 1
    } else {
        return 0
    }
    
}

使用三目运算符:

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

2.switch case

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 case
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)
}

我平时用switch相对少一些,感觉写起来有点麻烦。

3.对象配置/策略模式

对象配置看起来跟 策略模式 差不多,都是根据不同得参数使用不同得数据/算法/函数。

策略模式就是将一系列算法封装起来,并使它们相互之间可以替换。被封装起来的算法具有独立性,外部不可改变其特性。

接下来我们用对象配置的方法实现一下上述的例子

let type = 'A'

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

案例1 商场促销价
根据不同的用户使用不同的折扣,如:普通用户不打折,普通会员用户9折,年费会员8.5折,超级会员8折。

if-else大家肯定知道,那么使用对象配置呢?

// 获取折扣 -- 使用对象配置/策略模式
const getDiscount = (userKey) => {
    // 我们可以根据用户类型来生成我们的折扣对象
    let discounts = {
        '普通会员': 0.9,
        '年费会员': 0.85,
        '超级会员': 0.8,
        'default': 1
    }
    return discounts[userKey] || discounts['default']
}
console.log(getDiscount('普通会员')) // 0.9

从上面按理可看出,使用对象配置比if-lese可读性要搞,后续若需要添加用户折扣只需要修改折扣对象就行。

对象配置不一定非要使用对象去管理我们键值对,还可以使用 Map去管理。

// 获取折扣 -- 使用对象配置/策略模式
const getDiscount = (userKey) => {
    // 我们可以根据用户类型来生成我们的折扣对象
    let discounts = new Map([
        ['普通会员', 0.9],
        ['年费会员', 0.85],
        ['超级会员', 0.8],
        ['default', 1]
    ])
    return discounts.get(userKey) || discounts.get('default')
}
console.log(getDiscount('普通会员')) // 0.9

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

假如财务部要求我们提供一段代码来实现这个核算逻辑,我们要怎么实现呢?

if-else就不写了。

let strategies =new Map([
['A',4],
['B',3],
['C',2]
])
const caluteBonus = (performance,salary)=>{
return strategies.get(performance)*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
  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值