Multiple writing methods for judgment in javascript

A more elegant way to write complex judgments in JavaScript

Summary:  Writing code is an art.

Fundebug is authorized to reprint, and the copyright belongs to the original author.

premise

When we write js code, we often encounter complex logic judgments. Usually, you can use if/else or switch to realize multiple condition judgments, but this will have a problem. As the logic complexity increases, the if/ Else/switch will become more and more bloated and unintelligible, so how to write judgment logic more elegantly, this article will take you to try.

for example

First look at a piece of code

/** 
 * Button click event 
 * @param {number} status Activity status: 1 group in progress 2 group failed to start 3 product sold out 4 group successfully opened 5 system canceled 
 */ 
const onButtonClick = (status)=>{ 
  if( status == 1){ 
    sendLog('processing') 
    jumpTo('IndexPage') 
  }else if(status == 2){ 
    sendLog('fail') 
    jumpTo('FailPage') 
  }else if(status == 3){ 
    sendLog('fail') 
    jumpTo('FailPage') 
  }else if(status == 4){ 
    sendLog('success') 
    jumpTo('SuccessPage') 
  }else if(status == 5){ 
    sendLog('cancel') 
    jumpTo('CancelPage') 
  }else { 
    sendLog('other')
    jumpTo('Index')
  }
}

You can see the click logic of this button through the code: do two things according to different activity states, send log buried points and jump to the corresponding page, you can easily propose a rewrite plan for this code, switch comes out:

/** 
 * Button click event 
 * @param {number} status Activity status: 1 group in progress 2 group failed 3 product sold out 4 group successfully opened 5 system canceled 
 */ 
const onButtonClick = (status)=>{ 
  switch ( status){ 
    case 1: 
      sendLog('processing') 
      jumpTo('IndexPage') 
      break 
    case 2: 
    case 3: 
      sendLog('fail') 
      jumpTo('FailPage') 
      break   
    case 4: 
      sendLog('success') 
      jumpTo(' SuccessPage') 
      break 
    case 5: 
      sendLog('cancel') 
      jumpTo('CancelPage') 
      break 
    default: 
      sendLog('other'))
      jumpTo('Index')
      break
  }
}

Well, this looks much clearer than if/else, and the careful students also found a little trick. When the logic of case 2 and case 3 are the same, the execution statement and break can be omitted, and the case of case 2 will automatically execute the case 3 logic.

At this time, some students will say that there is a simpler way of writing:

const actions = {
  '1': ['processing','IndexPage'],
  '2': ['fail','FailPage'],
  '3': ['fail','FailPage'],
  '4': ['success','SuccessPage'],
  '5': ['cancel','CancelPage'],
  'default': ['other','Index'],
}
/**
 * 按钮点击事件
 * @param {number} status 活动状态:1开团进行中 2开团失败 3 商品售罄 4 开团成功 5 系统取消
 */
const onButtonClick = (status)=>{
  let action = actions[status] || actions['default'],
      logName = action[0],
      pageName = action[1]
  sendLog(logName)
  jumpTo(pageName)
}

上面代码确实看起来更清爽了,这种方法的聪明之处在于:将判断条件作为对象的属性名,将处理逻辑作为对象的属性值,在按钮点击的时候,通过对象属性查找的方式来进行逻辑判断,这种写法特别适合一元条件判断的情况。

是不是还有其他写法呢?有的:

const actions = new Map([
  [1, ['processing','IndexPage']],
  [2, ['fail','FailPage']],
  [3, ['fail','FailPage']],
  [4, ['success','SuccessPage']],
  [5, ['cancel','CancelPage']],
  ['default', ['other','Index']]
])
/**
 * 按钮点击事件
 * @param {number} status 活动状态:1 开团进行中 2 开团失败 3 商品售罄 4 开团成功 5 系统取消
 */
const onButtonClick = (status)=>{
  let action = actions.get(status) || actions.get('default')
  sendLog(action[0])
  jumpTo(action[1])
}

这样写用到了es6里的Map对象,是不是更爽了?Map对象和Object对象有什么区别呢?

  1. 一个对象通常都有自己的原型,所以一个对象总有一个”prototype”键。
  2. 一个对象的键只能是字符串或者Symbols,但一个Map的键可以是任意值。
  3. 你可以通过size属性很容易地得到一个Map的键值对个数,而对象的键值对个数只能手动确认。

我们需要把问题升级一下,以前按钮点击时候只需要判断status,现在还需要判断用户的身份:

/**
 * 按钮点击事件
 * @param {number} status 活动状态:1开团进行中 2开团失败 3 开团成功 4 商品售罄 5 有库存未开团
 * @param {string} identity 身份标识:guest客态 master主态
 */
const onButtonClick = (status,identity)=>{
  if(identity == 'guest'){
    if(status == 1){
      //do sth
    }else if(status == 2){
      //do sth
    }else if(status == 3){
      //do sth
    }else if(status == 4){
      //do sth
    }else if(status == 5){
      //do sth
    }else {
      //do sth
    }
  }else if(identity == 'master') {
    if(status == 1){
      //do sth
    }else if(status == 2){
      //do sth
    }else if(status == 3){
      //do sth
    }else if(status == 4){
      //do sth
    }else if(status == 5){
      //do sth
    }else {
      //do sth
    }
  }
}

原谅我不写每个判断里的具体逻辑了,因为代码太冗长了。

原谅我又用了if/else,因为我看到很多人依然在用if/else写这种大段的逻辑判断。

从上面的例子我们可以看到,当你的逻辑升级为二元判断时,你的判断量会加倍,你的代码量也会加倍,这时怎么写更清爽呢?

const actions = new Map([
  ['guest_1', ()=>{/*do sth*/}],
  ['guest_2', ()=>{/*do sth*/}],
  ['guest_3', ()=>{/*do sth*/}],
  ['guest_4', ()=>{/*do sth*/}],
  ['guest_5', ()=>{/*do sth*/}],
  ['master_1', ()=>{/*do sth*/}],
  ['master_2', ()=>{/*do sth*/}],
  ['master_3', ()=>{/*do sth*/}],
  ['master_4', ()=>{/*do sth*/}],
  ['master_5', ()=>{/*do sth*/}],
  ['default', ()=>{/*do sth*/}],
])

/**javascript
 * 按钮点击事件
 * @param {string} identity 身份标识:guest客态 master主态
 * @param {number} status 活动状态:1 开团进行中 2 开团失败 3 开团成功 4 商品售罄 5 有库存未开团
 */
const onButtonClick = (identity,status)=>{
  let action = actions.get(`${identity}_${status}`) || actions.get('default')
  action.call(this)
}

上述代码核心逻辑是:把两个条件拼接成字符串,并通过以条件拼接字符串作为键,以处理函数作为值的Map对象进行查找并执行,这种写法在多元条件判断时候尤其好用。

当然上述代码如果用Object对象来实现也是类似的:

const actions = {
  'guest_1':()=>{/*do sth*/},
  'guest_2':()=>{/*do sth*/},
  //....
}

const onButtonClick = (identity,status)=>{
  let action = actions[`${identity}_${status}`] || actions['default']
  action.call(this)
}

如果有些同学觉得把查询条件拼成字符串有点别扭,那还有一种方案,就是用Map对象,以Object对象作为key:

const actions = new Map([
  [{identity:'guest',status:1},()=>{/*do sth*/}],
  [{identity:'guest',status:2},()=>{/*do sth*/}],
  //...
])

const onButtonClick = (identity,status)=>{
  let action = [...actions].filter(([key,value])=>(key.identity == identity && key.status == status))
  action.forEach(([key,value])=>value.call(this))
}

是不是又高级了一点点?

这里也看出来Map与Object的区别,Map可以用任何类型的数据作为key。

我们现在再将难度升级一点点,假如guest情况下,status1-4的处理逻辑都一样怎么办,最差的情况是这样:

const actions = new Map([
  [{identity:'guest',status:1},()=>{/* functionA */}],
  [{identity:'guest',status:2},()=>{/* functionA */}],
  [{identity:'guest',status:3},()=>{/* functionA */}],
  [{identity:'guest',status:4},()=>{/* functionA */}],
  [{identity:'guest',status:5},()=>{/* functionB */}],
  //...
])

好一点的写法是将处理逻辑函数进行缓存:

const actions = ()=>{
  const functionA = ()=>{/*do sth*/}
  const functionB = ()=>{/*do sth*/}
  return new Map([
    [{identity:'guest',status:1},functionA],
    [{identity:'guest',status:2},functionA],
    [{identity:'guest',status:3},functionA],
    [{identity:'guest',status:4},functionA],
    [{identity:'guest',status:5},functionB],
    //...
  ])
}

const onButtonClick = (identity,status)=>{
  let action = [...actions()].filter(([key,value])=>(key.identity == identity && key.status == status))
  action.forEach(([key,value])=>value.call(this))
}

这样写已经能满足日常需求了,但认真一点讲,上面重写了4次functionA还是有点不爽,假如判断条件变得特别复杂,比如identity有3种状态,status有10种状态,那你需要定义30条处理逻辑,而往往这些逻辑里面很多都是相同的,这似乎也是笔者不想接受的,那可以这样实现:

const actions = ()=>{
  const functionA = ()=>{/*do sth*/}
  const functionB = ()=>{/*do sth*/}
  return new Map([
    [/^guest_[1-4]$/,functionA],
    [/^guest_5$/,functionB],
    //...
  ])
}

const onButtonClick = (identity,status)=>{
  let action = [...actions()].filter(([key,value])=>(key.test(`${identity}_${status}`)))
  action.forEach(([key,value])=>value.call(this))
}

这里Map的优势更加凸显,可以用正则类型作为key了,这样就有了无限可能,假如需求变成,凡是guest情况都要发送一个日志埋点,不同status情况也需要单独的逻辑处理,那我们可以这样写:

const actions = ()=>{
  const functionA = ()=>{/*do sth*/}
  const functionB = ()=>{/*do sth*/}
  const functionC = ()=>{/*send log*/}
  return new Map([
    [/^guest_[1-4]$/,functionA],
    [/^guest_5$/,functionB],
    [/^guest_.*$/,functionC],
    //...
  ])
}

const onButtonClick = (identity,status)=>{
  let action = [...actions()].filter(([key,value])=>(key.test(`${identity}_${status}`)))
  action.forEach(([key,value])=>value.call(this))
}

也就是说利用数组循环的特性,符合正则条件的逻辑都会被执行,那就可以同时执行公共逻辑和单独逻辑,因为正则的存在,你可以打开想象力解锁更多的玩法,本文就不赘述了。

总结

本文已经教你了8种逻辑判断写法,包括:

  1. if/else
  2. switch
  3. 一元判断时:存到Object里
  4. 一元判断时:存到Map里
  5. 多元判断时:将condition拼接成字符串存到Object里
  6. 多元判断时:将condition拼接成字符串存到Map里
  7. 多元判断时:将condition存为Object存到Map里
  8. 多元判断时:将condition写作正则存到Map里

至此,本文也将告一段落,愿你未来的人生里,不只是有if/else/switch。

Guess you like

Origin blog.csdn.net/Qianliwind/article/details/83858643