Say goodbye to code redundancy! Teach you how to write if else gracefully

preface:
When we write js code, we often encounter complex logic judgment. Usually, you can use if/else or switch to realize multiple conditional judgment, but there will be a problem. With the increase of logic complexity, the if/else/switch in the code will become more and more bloated, and the readability will become worse and worse, so we can't understand it. How to write judgment logic more gracefully is analyzed below:

Simple if else

When your business is a simple two-sided judgment (either true or false):
You might write that

 // param {Boolean} falg :true or false
 let txt = '';
 if(falg){
    txt = "success"
 }else{
    txt = "fail"
 }

This is not the best way to write. At the same time, the code is not concise enough. Change the idea and directly perform the three eye operation:

let txt = flag  ? "success" : "fail" ;

When multiple if else appear

You might write that

 // param {status} status activity status: 1: success 2: failure 3: in progress 4: not started
 let txt = '';
 if(status == 1){
    txt = "success" ;
 }else if(status == 2){
    txt = "fail" ;
 }else if(status == 3){
     txt = "have in hand" ;
 }else{
    txt = "Not started" ;
 }

First, you might think of switch case

let txt = '';
switch(status){
    case 1:
     txt = "success" ;
     break ;
    case 2:
     txt = "success" ;
     break ;
    case 3:
     txt = "have in hand" ;
     break ;
    default:
      txt = "Not started" ;
}

This multi condition judgment has many conditions and the code is very bloated. We might as well try using the form of key value of the object. The above code continues to be optimized:

const statusMap = {
    1:"success",
    2:"fail",
    3:"have in hand",
    4:"Not started"
}

Call statusMapp[status] directly to solve the problem!
wooo ~ you will find that the code is so simple!!! Do you feel comfortable looking at it~

Using es6 Map

If you think the above code is not ideal, you can try Map

const actions = new Map([
  [1, "success"],
  [2, "fail"],
  [3, "have in hand"],
  [4, "Not started"]
 ])

Call direct actions Get (status) solution!

We need to upgrade the problem. In the past, we only need to judge the status when clicking the button. Now we also need to judge the user's identity:

/**
 * Button click event
 * @param {number} status Activity status: activity status: 1: success 2: failure 3: in progress 4: not started
 * @param {string} identity Identity: admin administrator user user
 */
const handle = (status,identity)=>{
  if(identity == 'admin'){
    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 == 'user') {
    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
    }
  }
}

Forgive me for not writing the specific logic in each judgment, because the code is too lengthy.

Forgive me for using if/else again, because I see that many people are still using if/else to write such long logical judgments.
So, how to write elegant and concise???

Similarly, use Map

const actions = new Map([
  ['admin_1', ()=>{/*do sth*/}],
  ['admin_2', ()=>{/*do sth*/}],
  ['admin_3', ()=>{/*do sth*/}],
  ['admin_4', ()=>{/*do sth*/}],
  ['admin_5', ()=>{/*do sth*/}],
  ['user_1', ()=>{/*do sth*/}],
  ['user_2', ()=>{/*do sth*/}],
  ['user_3', ()=>{/*do sth*/}],
  ['user_4, ()=>{/*do sth*/}],
  ['user_5, ()=>{/*do sth*/}],
  ['default', ()=>{/*do sth*/}],
])
const handle  = (identity,status)=>{
  let action = actions.get(`${identity}_${status}`) || actions.get('default')
  action.call(this)
}

Of course, if the above code is implemented with an Object object Object, it is similar:

const actions = {
  'admin_1':()=>{/*do sth*/},
  'admin_2:()=>{/*do sth*/},
  'admin_3:()=>{/*do sth*/},
  //....
}

What if the processing logic of status1-4 is the same under the condition of admin? The worst case is this:

const actions = new Map([
  ['admin_1', ()=>{/*function A*/}],
  ['admin_2', ()=>{/*function A*/}],
  ['admin_3', ()=>{/*function A*/}],
  ['admin_4', ()=>{/*function A*/}],
  ['admin_5', ()=>{/*function B*/}],
])

Obviously, function A is written repeatedly for 4 times, which is not a good way. Then we try to cache function A and function B

const actions = ()=>{
  const functionA = ()=>{/*do sth*/}
  const functionB = ()=>{/*do sth*/}
  return new Map([
   ['admin_1', functionA],
   ['admin_2', functionA],
   ['admin_3', functionA],
   ['admin_4', functionA],
   ['admin_5', functionB],
    //...
  ])
}

If there are more than 10 or more status es and the code is also bloated, we can add regular matching to the above code:

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

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

Based on the above form, we have many changes to adapt to our business

For example, the scenario is like this: identity ID: admin administrator user user
admin,1-4, execute function a, 5 execute function B, 5-9 execute function C, and more than 9 execute function D. We can change the following codes:

const actions = ()=>{
  const functionA = ()=>{/*do sth*/}
  const functionB = ()=>{/*do sth*/}
  const functionC = ()=>{/*do sth*/}
  const functionD = ()=>{/*do sth*/}
  return new Map([
    [/^admin_[1-4]$/,functionA],
    [/^admin_5$/,functionB],
    [/^admin_[6-9]$/,functionC],
    [/^admin_[1-9]\d$/,functionD],
    //...
  ])
}

Summary:

This article has taught you eight ways to write logical judgment, including:

1: if else

2: Binocular operation

3: In unary judgment: use the key value of object

4: For unitary judgment: use Map

5: In case of multiple judgment: concatenate the condition into a string and store it in the Object

6: In case of multiple judgment: splice the condition into a string and store it in the Map

7: When making multiple judgments: concatenate the condition into a string and store it in the Map for use with regular

last:

  • Everyone feels that it is well written. You can praise and pay attention to it~

Tags: Javascript JQuery

Posted by seanrock on Thu, 19 May 2022 09:17:19 +0300