preface
Have you ever written or seen the following code in your actual development
function check() {
if(...). {if(...). {if(...). ) {if(...). {if(...). {console.log(...)
if(...). {console.log(...)
if(...). {console.log(...)
if(...). {... }}else{... }}else{... }}else{... }}else if(...). {if(...). {if(...). {if(...). {if(...). {console.log(...)
if(...). {console.log(...)
if(...). {console.log(...)
} else{... }}else{... }}else{... }}else{... }}else{... }}else{... }}else{... }}else{... }}else{... }}else{... }}Copy the code
Is not an instant feeling big head, a day of good mood also disappeared
Next, THE author will provide several optimization schemes, hoping to help you.
- Single if statement optimization
- If /else statement optimization
- Single if multi-condition optimization
- Multiple ELSE if branches are optimized
Single if statement optimization
Before optimization
if (flag) {
this.handleFn()
}
Copy the code
The optimized
flag && this.handleFn()
// handleFn is a normal function
Copy the code
This writing method is more clear, concise, easy to read! In addition, if there are many if statements that execute the same function, we can use “logic and” or “logic or” to combine them into a single expression. If our independent conditional judgments can be viewed as scenarios of the same check, the intent of one check is clearly superior to the readability of multiple conditional checks. Let’s look at a code snippet:
if(! (staffInfo.patientName && staffInfo.phone)) {// doSomething}...if(! (staffInfo.phone && staffInfo.idCardNum)) {// doSomething
}
Copy the code
We can modify the above code to look like this by merging the logic:
if(! (staffInfo.patientName && staffInfo.phone) || ! (staffInfo.phone && staffInfo.idCardNum)){// doSomething
}
Copy the code
If /else statement optimization
If /else can be said to be encountered most frequently in a project, and these two strategies can usually be optimized
- The policy
- Ternary operator
The policy
For example, in the user login scenario, if the user name and password input fields are empty, the user is prompted “User name and password cannot be empty”. If there is a value, the login operation is performed. Before optimization
if (user && password) {
// Logical processing
} else {
throw('Username and password cannot be empty! ')}Copy the code
The optimized
if(! user || ! password)return throw('Username and password cannot be empty! ')
// Logical processing
Copy the code
When submitting a form, we need to exclude the contents that are not submitted in accordance with our requirements in advance. Usually, when the form submission meets our requirements more than we submit successfully, the exclusion strategy is a good choice.
Ternary operator
The sample a
let allow = null
if(age > =18) {allow ='through';
} else {
allow = 'refuse';
}
/ / after optimization
let allow = age >= 18 ? 'through' : 'refuse'
Copy the code
Example 2
if (flag) {
success();
} else {
fail();
}
/ / after optimization
flag ? success() : fail();
Copy the code
Ternary operators require only one line of code compared to if/else.
Single if multi-condition optimization
Before optimization
function test(type) {
if (type === 'jpg' || type === 'png' || type === 'gif' || type === 'svg') {
console.log("This file is a picture"); }}Copy the code
The optimized
function test(type) {
const imgArr = ['jpg'.'png'.'gif'.'svg']
if (imgArr.includes(type)) {
console.log("This file is a picture")}}Copy the code
Multiple ELSE if branches are optimized
Multiple Else Ifs are often a poor choice, leading to complex designs, poor code readability, and possibly difficult refactoring.
if (this.type === 'A') {
this.handleA();
} else if (this.type === 'B') {
this.handleB();
} else if (this.type === 'C') {
this.handleC();
} else if (this.type === 'D') {
this.handleD();
} else {
this.handleE();
}
Copy the code
We often encounter multiple else if conditional code, and the else if code gets bigger and bigger as the logic complexity increases.
The code with different conditional branches has a high degree of coupling, the previous conditional judgment will affect the subsequent code flow, and this kind of code is difficult to maintain in the subsequent development. We can optimize code with switches, key-values, and maps.
switch
switch(val){
case 'A':
handleA()
break
case 'B':
handleB()
break
case 'C':
handleC()
break
case 'D':
handleD()
break
}
Copy the code
key-value
While the switch statement is logically simpler than the else if statement, the code itself is a bit much. In fact, our object enumerates key values that associate a condition with a particular operation.
let enums = {
'A': handleA,
'B': handleB,
'C': handleC,
'D': handleD,
'E': handleE
}
function action(val){
let handleType = enums[val]
handleType()
}
Copy the code
This approach eliminates all conditional statements and uses key-value objects to store the relationship between conditions and operations. When we need to execute code based on conditions, we no longer need to use an else if or switch statement to handle the corresponding action, we can simply extract the corresponding function handleType from it and execute it.
Map
In fact, we can use maps to further optimize our code.
Map has many advantages over Object
- The key of an object can only be a string or symbol, whereas the key of a Map can be any type of value.
- We can easily obtain the number of key/value pairs for a Map using the Map Size attribute, whereas the number of key/value pairs for an object can only be determined manually.
- Has extremely fast search speed.
The above example can be optimized as follows:
let enums = new Map([['A', handleA],
['B', handleB],
['C', handleC],
['D', handleD],
['E', handleE]
])
function action(val){
let handleType = enums(val)
handleType()
}
Copy the code
If we encounter multiple layers of complex conditions, the Map statement is even more advantageous!
if (mode == 'kline') {
if (this.type === 'A') {
this.handleA()
} else if (this.type === 'B') {
this.handleB()
} else if (this.type === 'C') {
this.handleC()
} else if (this.type === 'D') {
this.handleD()
}
} else if ((mode = 'depth')) {
if (this.type === 'A') {
this.handleA()
} else if (this.type === 'B') {
this.handleB()
} else if (this.type === 'C') {
this.handleC()
} else if (this.type === 'D') {
this.handleD()
}
}
Copy the code
For such a complex scenario as described above, can Map be used to optimize it? All we really need to do is concatenate the different judgment statements into a string so that we can associate conditions and actions in key-value format.
let enums = new Map([['kline_A', handleKlineA],
['kline_B', handleKlineB],
['kline_C', handleKlineC],
['kline_D', handleKlineD],
['kline_E', handleKlineE],
['depth_A', handleDepthA],
['depth_B', handleDepthB],
['depth_C', handleDepthC],
])
function action(mode, type){
let key = `${mode}_${type}`
let handleType = enums(key)
handleType()
}
Copy the code
There is also a view that if… else… The language itself is the underlying logic, is unable to continue to optimize, the so-called optimization is nothing more than from logic or from the form of syntax, and did not completely change if… else… The essence of. I am not sure about this.