preface

In the daily development of the front end, it is most common to execute different code logic according to different conditions, and our most commonly used logic is if,else. As our conditions became more complex, we found that the code did several things that made subsequent maintenance and extension more difficult.

Note: This article does not mean that all if and else statements need to be optimized, but refers to the future development and maintenance has caused trouble, or the risk of the code is not strict, we can consider a direction.

Note: this article refers to all the articles about if/else published by The Nuggets so far. It is also hoped that when you learn some knowledge, you will try to analyze a knowledge point comprehensively, judge the original scene, and what is good about this code technique, why I use it.

Classical conditional writing

// Case 1: multiple critical values
if(a === 1){
   code xxx
 } else if(a>==2 && a<==10){
   code xxx
 } else if(a>==11){
   code xxx
 }

// Case 2: nested structure
if(age>18) {if(money>==1000){
	}else{}}else if(age <== 10) {if(money>==1000){
	}else{}}// Because of the different values of the participation conditions,
// For example, if you have two arguments and two values for booleans, then there are four combinations. If each is different, you need to write at least four blocks
 if(a && b){
 }else if(! a && b){ }else if(a && ! b){ }else{}// Return as soon as the return condition is satisfied
if(case 1){
code xxx;
return 
}
if(case 2){
code xxx;
return 
}
if(case 3){
code xxx;
return 
}
Copy the code

The purpose of listing the above scenarios is to provide a more in-depth list of more specific solutions for different situations.

Beginner: Code skills

There are a number of code tricks we often see in front ends with a bit of experience, and these code tricks are also applicable when it comes to conditional statement optimization.

switch case

Switch case is probably one of the easiest ways to optimize, and without understanding the cost and use cost, the limitation is to limit the case, which requires switching strategy based on a key value, not multiple values. Therefore, if you want to switch to achieve better results, there may be two preconditions: 1 your qualification is already a key value. 2 Is that you have converted multiple value judgments into one value when deciding to switch.

// Here is a reminder
// case can write conditional judgment
let a =1 
switch(true) {case a<10: {console.log(0);
    break;
  }
  case a === 10: {console.log(10);
    break; }}// Multiple cases can execute the same code snippet
switch (a){
  case 2:case4:{
  }
  default: {}}// If break is not written, the code segment 1,555 will be printed separately,
// Start with the first one that meets the condition and continue to execute logic, unless you encounter a break later, you need to pay attention to this blind spot and can be exploited in some cases
let a = 10;
switch(a){
  case 3: {console.log(4444)}
  case 10: {console.log(1); }case 2: {console.log(555);break}
  default: {console.log(a);}
}
Copy the code

The extraction judgment condition defines the function

In the above logic, we can see that there is a lot of code that makes logical judgments about key conditions, so first of all, you just need the result of a judgment to execute a certain piece of code for different conditions. From this point of view, we can define all judgment statements as functions that return a unique value that determines which scheme to use and which code to execute, using input criteria.

Let’s take the third case above, for example, and actually rewrite it to look like this:

// You can gather all the parameters together and write a judgment that returns a unique identifier for which code to use
const judgeStragety = (a,b){
 if(a && b){
 	return 'case1'
 }else if(! a && b){return 'case2'
 }else if(a && ! b){return 'case3'
 }else{
    return 'case4'}}// Execute the code, and then execute the code segment corresponding to the policy identifier
let stragety = judgeStragety(a,b)

// There are even cases where you feel that certain criteria are different, and you can even extract separate functions based on certain criteria
// This has the advantage of being more decoupled,
// The value of a logical statement can be determined by the name of your function
if(judgeA(a,b,c)){
}
if(judgeB(b,f)){
} 

Copy the code

Extract common logic from code snippets and encapsulate functions

Functional programming is one of the basic thinking of the front end. As first-class citizens of programming, functions should always remember to encapsulate redundant and optimized codes.

For example, I saw some people write code like this today, which is obviously redundant. Since the code has common logic, it should be separated into a function, which can make the code more maintainable later on.

if(a === 1) {console.log(1111)
	alert(10)}else if(a === 2) {console.log(2222)
	alert(20)}else{
	code xxx
}

const action = code= >{
 console.log(1111*code)
  alert(10*code)
}


if(a===1){
action(1)}else if(a===2){
action(2)}else {
code xxx
}
Copy the code

Short circuit and &&, logic or | |

This part in exotic curiosity-a solution looking for my another article has a very detailed description skills, can click to view: www.yuque.com/robinson/js…

For example: logic and execution function, a && b && fn(), instead of if(a && b){fn()}

Such as logic or for default rendering, let MSG = error. The MSG | | ‘default display information’

The ternary judgment

The triadic judgment is also one of the ways to reduce the condition judgment, because it has given the two processing results with different conditions through the way of assignment statement.

let desc = age > 18 ? ‘Adult’ : ‘minor’

Intermediate: Data structure + functional programming

The data structure

For some common data structures, there are many that can be used to simplify our common logic statements and code execution strategies.

/ / the original
if(sex === 0){
 desc = 'woman'
}else if(sex === 1){
	desc = 'male'
}else{
	desc = ' '
}
// use a dictionary to make a one-to-one correspondence
let sexDict = {
 0:'woman'.1:'male'
}
let desc = sexDict[sex]

// Use arrays to collect multiple conditional values
/ / the original
if(a === 0 || a ===4){
  code xxx
}
/ / now,
const statusArr = [0.4]
if(statusArr.includes(status)){

}


The value of a map is that you can set keys to re, objects, and so on
let vaildScore = 'score_2'
let scoreHandler = new Map()
scoreHandler.set(/^score_[1-9]{1}/, () = >console.log('vip1'))
scoreHandler.set(/^score_0/, () = >console.log('vip0'))
scoreHandler.forEach(function(value,key){
  if(key.test(vaildScore)){
    value()
    return}})Copy the code

The functional programming

  • purity
  • Currie,
  • immutability
  • Function composition

Advanced: Design mode

The strategy pattern

According to different conditions, using no algorithm, a conclusion is drawn. Language finches links: www.yuque.com/robinson/de…

const PriceStrategy = function(){
// Internal algorithm object
    const stragtegy = {
       return30:function(price){},return60:function(price){},}// The policy algorithm calls the interface
   return function(cheaperLevel,price){
       returnstragtegy[cheaperLevel] && stragtegy[cheaperLevel](price) } }// The usage mode
let price = PriceStrategy('return30'.'321.56')
console.log(price)
Copy the code

The state pattern

According to different conditions, can resolve for the various states, perform packaging function of different state, the state pattern address: www.yuque.com/robinson/de…

let status = light.status
switch(status){
    case 'on':console.log('light is on ,we can read books');
    break;
    case 'off':console.log('light is off ,we can not see anything');
    break;
     case 'error':console.log('light is error ,we can not do any operation');
    break;
}

function lightTip(status){
    case 'on':console.log('light is on ,we can read books');
    break;
    case 'off':console.log('light is off ,we can not see anything');
    break;
     case 'error':console.log('light is error ,we can not do any operation');
    break;
}
// Get the status to perform the operation
let status = light.status 
lightTip(status)
// Change state execution in other logic
light.status = 'off'
// Continue execution
let status = light.status 
lightTip(status)

// Think abstractly as an electric lamp
/ / the light class
class light{
  setState(state){
    this.state = state
  }
  getState(){
      return this.state.status
  }
  request(){
    return this.state.handler()
  }
} 
/ / state
class lightState{
  constructor() {this.status = ' '
  }
  handler(context){
    console.error('Not in any valid state')}}// Status Indicates the startup status
class onState extends lightState{
  constructor() {super(a);this.status='on'
  }
  handler(){
    console.log('light is on ,we can read books')}}// Close the state implementation
class offState extends lightState{
  constructor() {super(a);this.status='off'
  }
  handler(){
    console.log('light is off ,we can not see anything')}}let lightDemo = new light()
lightDemo.setState(new onState())
lightDemo.request()

lightDemo.setState(new offState())
lightDemo.request()

Copy the code

Responsibility chain pattern — circular matching

Define n kinds of judgment conditions and the execution function, when not sure which specific execution, circular judgment all queue whether there are available functions in line with the conditions, advantages, flexible and convenient, can flexibly add or reduce the function; Disadvantages, increase unnecessary function running costs, cannot return early.

let dutyArr = []
dutyArr.push({
	match:(a,b) = >{},action:(a)= >{
 }           
})

dutyArr.push({
	match:(a,b) = >{},action:(a)= >{
 }           
})

dutyArr.forEach(function(item){
  if(item.natch(ab)){
    item.action()
  }
})

Copy the code

summary

A glimpse of the leopard can be seen. When we learn programming, we should be good at starting from a point, thinking about various possibilities, various application scenarios, and what skills are suitable for use, rather than seeing one and knowing one and using one.

This article provides a general way of thinking when dealing with code logic from small to large, from elementary to advanced. The ideas sorted out in this article are not the most complete and authoritative, but to help you explore more systematically or in a more specific way when dealing with a technical topic.

link

My js language booklet finch: www.yuque.com/robinson/js…