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

1,799 阅读1分钟

消除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获得更好的代码结构(英文文档-需翻墙)