Optimization of conditional statements Aspects

Foreword

In the daily development of the front end, to execute different code depending on logical conditions are the most common, however, and our most popular logic is, if, else up. When our conditions become more complex, we will find that the code will appear the following situations, let's follow-up maintenance and expansion becomes more difficult.

Note : This article is not to say that all of if, else statements are necessary to optimize, but refers to the subsequent development and maintenance have caused trouble, or when the code is not strict risk increases, a direction that we can consider.

Special Note : This reference to all articles about if / else Nuggets released so far, but also hope that we learn to know a little time as possible a comprehensive analysis of knowledge, judge the original scene, and what good skills such code where, why I use.

Classic conditional statement written

// 情况一 :多种判断临界值
if(a === 1){
   code xxx
 } else if(a>==2 && a<==10){
   code xxx
 } else if(a>==11){
   code xxx
 }

// 情况二 :嵌套结构
if(age>18){
   if(money>==1000){
	}else{
    }
 } else if(age <== 10){
 	if(money>==1000){
	}else{
    }
 }
 
//情况三 :因为参与条件的不同值情况,
//比如下面这种2个参数,布尔型2个值,那么组合起来便有4种,如果每个都不同,你最少要写4个语句块
 if(a && b){
 }else if(!a && b){
 }else if(a && !b){
 }else{
 }


//情况四 :是针对函数而言的,最近比较流行的写法,当满足返回条件时,尽早返回
if(case 1){
code xxx;
return 
}
if(case 2){
code xxx;
return 
}
if(case 3){
code xxx;
return 
}
复制代码

The reason why several scenarios listed above, the following is to be able to more in-depth list of more targeted solutions for different situations.

Primary: Code Tips

In the front end where many have had little experience, we can often see some code tips, tricks and code also applies when a conditional statement optimization.

switch case

switch case is probably one of the most easy to optimize the way we think, and do not understand the cost and use cost, restrictions on the case is relatively limited, need to switch strategy based on a key value, not a multiple values, so if you want switch to achieve better results, there may be two premises: 1 your qualification has always been a key value 2 is your decision to switch in time, the judge has already converted more than one value has become a value (As for how to convert a below I can see).

//这里需要提醒给大家的是
// case中可以写条件判断
let a =1 
switch(true){
  case a<10:{
  	console.log(0);
    break;
  }
  case a === 10:{
  	console.log(10);
    break;
  }  
}
// 多个case可以执行同一个代码段
switch (a){
  case 2:case4:{
  }
  default:{
  } 
}

// 如果不写break,会执行的代码段1,555会分别打印出来,
//也就是从第一个符合条件的开始,不断执行逻辑,除非后续遇到break,你需要注意这个盲点,也可以某种情况下利用
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);}
}
复制代码

Disengagement determination condition defined function

In the above logic, we can see a lot of the key conditions for logical judgment of code, then first of all, for the code segment under different conditions, you just need the result of a judgment, then execute a piece of code. From this starting point, we can all judge sentences defined as a function, the function of this role is through the input conditions, a return can decide what programs to use, what unique value code execution.

The third case we take the above example, after we actually rewritten like this:

//你可以将所有的参数收集,综合写一个判断,返回使用哪种代码的唯一标识
const judgeStragety = (a,b){
 if(a && b){
 	return 'case1'
 }else if(!a && b){
   return 'case2'
 }else if(a && !b){
     return 'case3'
 }else{
    return 'case4'
 }
}

//执行代码中,你的使用便成了,然后执行对应策略标识的代码段便可以
let stragety = judgeStragety(a,b)

// 甚至有些情况下 你觉得某些判断条件都是不同的,你甚至可以依据某个判断条件抽离单独的函数
// 这样的好处便是,更解耦,
//别人也更能通过你的函数名,判断出这个逻辑语句的真正价值,不然 q === 1这种,真的别人看不懂
if(judgeA(a,b,c)){
}
if(judgeB(b,f)){
} 

复制代码

Code segments common logical disengagement, wrapper function

Programming is one of the basic functions of thinking front end, as a function of the programming of the first-class citizens, we must remember that moment for redundancy, with code optimization space encapsulation.

For example, I see the code written today, some people like this, obviously redundant code, since the code has a common logic, in respect of this part is pulled out of a function, follow-up can also make the code more maintainable.

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
}
复制代码

Shorted &&, || logical OR

This section has a very detailed description of the techniques, you can click to see my clever but useless in another article: www.yuque.com/robinson/js...

For example: performing a logical AND function, a && b && fn (), instead of if (a && b) {fn ()}

Such as a logical OR, a default assignment, let msg = error.msg || 'default display information'

Analyzing trinocular

Analyzing trinocular also reduce one determination condition because it has two conditions are not simultaneously processing results are given by way of an assignment statement.

let desc = age> 18 'adults':? 'minor'

Intermediate: programming function data structure +

data structure

For some common data structure, a lot can be used to simplify our common logical statements and code execution policy.

// 原来
if(sex === 0){
 desc = '女'
}else if(sex === 1){
	desc = '男'
}else{
	desc = ''
}
// 使用字典来做1对1 的对应关系
let sexDict = {
 0:'女',
  1:'男'
}
let desc = sexDict[sex]

// 使用数组收集多个条件值
//原来 
if(a === 0 || a ===4){
  code xxx
}
// 现在 
const statusArr = [0,4]
if(statusArr.includes(status)){

}


//使用map收集复杂值 map的价值就在于可以设置key为正则、对象等等
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
  }
})

复制代码

Functional Programming

  • Purity
  • Currying
  • Immutability
  • Function composition

Advanced: Design Patterns

Strategy Mode

For different conditions, without the use of algorithms, we come to a conclusion. Language bird link: www.yuque.com/robinson/de...

const PriceStrategy = function(){
// 内部算法对象
    const stragtegy = {
       return30:function(price){
        },
       return60:function(price){
        },
    }
// 策略算法调用接口
   return function(cheaperLevel,price){
       return stragtegy[cheaperLevel] && stragtegy[cheaperLevel](price)
   }
}

// 使用方式
let price = PriceStrategy('return30','321.56')
console.log(price)
复制代码

State mode

For different conditions, we can resolve various states, different states of execution wrapper function, the state of Address mode: 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;
}
// 获取状态执行操作
let status = light.status 
lightTip(status)
// 其他逻辑里更改状态执行
light.status = 'off'
// 继续执行
let status = light.status 
lightTip(status)

//思考抽象为电灯状态
// 电灯类
class light{
  setState(state){
    this.state = state
  }
  getState(){
      return this.state.status
  }
  request(){
    return this.state.handler()
  }
} 
// 状态类
class lightState{
  constructor(){
    this.status = ''
  }
  handler(context){
    console.error('不在任何有效状态')
  }
}
// 具体状态实现 启动状态
class onState extends lightState{
  constructor(){
    super();
    this.status='on'
  }
  handler(){
    console.log('light is on ,we can read books')
  }
}
// 关闭状态实现
class offState extends lightState{
  constructor(){
    super();
    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()

复制代码

Chain of Responsibility pattern matching cycle ---

Analyzing the definition of n conditions, and the function is executed when uncertain what particular execution cycle to determine whether there is available a function qualified, all the advantages of the queue, flexible, flexible or reduce additional function; disadvantages, an increase of unnecessary function operating costs, can not be returned as soon as possible.

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

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

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

复制代码

summary

Piece of a jigsaw, is evident. We learn to program, to be good at starting from a point, thinking every possible variety of usage scenarios for using what skills, rather than see one to know is with a a.

Is provided herein from small to large, from beginner to advanced, our common way of thinking when dealing with code logic, this paper collated idea nor the most complete, most authoritative, but help everyone in a respective one technical theme of time can be like more systematic or more specific and more to explore some.

Links

My bird js language booklet: www.yuque.com/robinson/js...

Reproduced in: https: //juejin.im/post/5d026b5d51882570ec01788b

Guess you like

Origin blog.csdn.net/weixin_33869377/article/details/93171546