消除switch语句以获得更好的代码结构

消除switch语句以获得更好的代码结构

  • 代码演化1:纯switch
function counter(state = 0, action) {
  switch (action.type) {
    case 'INCREMENT':
      return state + 1
    case 'DECREMENT':
      return state - 1
    default:
      return state
  }
}
复制代码
  • 用三元运算符代替
const counter = (state = 0, action) =>
  action.type === 'INCREMENT'   ? state + 1
  : action.type === 'DECREMENT' ? state - 1
                                : state
复制代码
  • 更换action.type ===,用对象本身的方法
function switchcase (cases, defaultCase, key) {
  if (cases.hasOwnProperty(key)) {
    return cases[key]
  } else {
    return defaultCase
  }
}
复制代码
  • 柯里化
const switchcase = cases => defaultCase => key =>
  cases.hasOwnProperty(key) ? cases[key] : defaultCase
  
const counter = (state = 0, action) =>
  switchcase({
    'INCREMENT': state + 1,
    'DECREMENT': state -1
  })(state)(action.type)
复制代码
  • 增加是否为函数检测
  const action = {
      type: 'INCREMENT'
    }
    const executeIfFunction = f =>
      f instanceof Function ? f() : f

    const switchcase = cases => defaultCase => key =>
      cases.hasOwnProperty(key) ? cases[key] : defaultCase

    const switchcaseF = cases => defaultCase => key =>
      executeIfFunction(switchcase(cases)(defaultCase)(key))

    const counter = (state = 0, action) =>
      switchcaseF({
        'INCREMENT': () => state + 1,
        'DECREMENT': () => state - 1
      })(state)(action.type)
    console.log(counter(0, action))
复制代码
  • switch应用--星期天转换
const switchcase = cases => defaultCase => key =>
      cases.hasOwnProperty(key) ? cases[key] : defaultCase
      
 const getDay = switchcase({
      0: 'Sunday',
      1: 'Monday',
      2: 'Tuesday',
      3: 'Wednesday',
      4: 'Thursday',
      5: 'Friday',
      6: 'Saturday'
    })('Unknown')
    const getCurrentDay = () => getDay(new Date().getDay())
    const day = getCurrentDay()
复制代码

参考链接---消除switch获得更好的代码结构(英文文档-需翻墙)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值