As we all know, in our daily code process, the most frequently used may be if/else condition judgment statement, I have also seen a full screen of if/else code, although it is not difficult to understand, but for code cleanliness fanatic people still hope to have a better way to change it. After all, we are ambitious programmers, so today I will use a way to modify the if/else code to make our code better organized
Calculator examples:
Use if/else code
function calculate(num1,num2,action) {
if (action === 'add') {
return num1 + num2
}else if (action === 'subtract') {
return num1 - num2
}else if(action === 'multiply') {
return num1 * num2
}else if (action === 'divide') {
return num1 / num2
}else {
return 'calculate is not recongnised.'}}Copy the code
The code above is easy to understand, passing in two arrays and an action to add, subtract, multiply and divide. This is if/else code, you can see that the logic is fairly clear, after all, the business is not complicated at this time. However, if the logic is very complex, this may not look so good, then Switch will be used for modification
Use switch to transform
function calculateWithSwitch(num1,num2,action) {
switch (action) {
case 'add':
return num1 + num2
case 'subtract':
return num1 - num2
case 'multiply':
return num1 * num2
case 'divide':
return num1 / num2
default:
return 'calculate is not recongnised.'}}Copy the code
After using the switch to rewrite the calculator code, we can feel better than if/else, at least in the case of many judgment conditions can be a little concise, but if we have too much logic, all written in the switch will not look good, so we will use the Object way to change
Use the Object mode to transform
function calculateWithObject(num1,num2,action) {
const actions = {
add: (a,b) = > a + b,
subtract: (a,b) = > a - b,
multiply:(a,b) = > a * b,
divide: (a,b) = > a / b
}
/ /? . Checks whether the function exists and calls it if so, otherwise returns the default string
returnactions[action]? .(num1,num2) ??'calculate is not recognised.'
}
Copy the code
It can be seen that the use of the object’s key to save the action behavior, split the logic into different functions, can greatly simplify our code, make the logic more clear
Conclusion:
In some logically complex cases, you can modify if/else statements by using Object keys