PrefaceWhen we write JavaScript, we often encounter some logical judgments, which can be implemented using if/else or switch. However, for complex judgments, too many conditions often make our code lengthy and reduce readability. So we need to optimize our code to make it more elegantπ. 1. Monadic Judgment 1.1 ExampleWe write a common if/else judgment function and then optimize it. const myFunction = (status) => { if (status === 1) { console.log("status1"); } else if (status === 2) { console.log("status2"); } else if (status === 3) { console.log("status3"); } }; 1.2 Put it into ObjectWe know that JavaScript's Object is actually an unordered collection of key-value pairs, which is why we can use it to store judgment conditions. For example, in the above case, the judgment condition is a numeric type, and the subsequent operation only uses a string. At this time, we can create an object and use the number and string used as the key name and corresponding value of the Object respectively. //Put the judgment condition into Object const statusObj = { 1: "status1", 2: "status2", 3: "status3", }; // Optimized function π const myFunction = (status) => { console.log(statusObj[status]); }; 1.3 Put it into MapIn addition to primitive objects, we can also use Map objects. Let's look at MDN's description of it: Map objects store key-value pairs and are able to remember the original insertion order of the keys. Any value (object or primitive) can be used as a key or a value. It is not difficult to see that the Map object is actually an enhanced version of the ordinary object. In particular, any value can be used as its key-value pair, which means that functions, regular expressions, etc. can also be used as its key or value, which greatly facilitates our operations of using it as a judgment. The details about the Map object will not be expanded here. //Put the judgment conditions into Map const statusMap = new Map([ [1, "status1"], [2, "status2"], [3, "status3"], ]); // Optimized function π const myFunction = (status) => { console.log(statusMap.get(status)); }; 2. Multiple Judgment 2.1 An exampleSince univariate judgments can be optimized, plural judgments can also be optimized. The following is a case with two judgment conditions. // Give an example π° const myFunction = (right, status) => { if (right === "administrator" && status === 1) { console.log("Administrator likes Wang Bingbing"); } else if (right === "administrator" && status === 2) { console.log("Administrator doesn't like Wang Bingbing"); } else if (right === "user" && status === 1) { console.log("User likes Wang Bingbing"); } else if (right === "user" && status === 2) { console.log("The user doesn't like Wang Bingbing"); } }; // Example with duplication π° const myFunction = (right, status) => { if (right === "administrator" && status === 1) { console.log("Administrator likes Wang Bingbing"); } else if (right === "administrator" && status === 2) { console.log("Administrator likes Wang Bingbing"); } else if (right === "user" && status === 1) { console.log("User likes Wang Bingbing"); } else if (right === "user" && status === 2) { console.log("User likes Wang Bingbing"); } }; 2.2 Put the judgment conditions into a string and put it into the ObjectBoth situations can also be optimized using Object. // Optimize "Example π°" //Put the judgment condition into Object const actionsObj = { "administrator-1": "Administrator likes Wang Bingbing", "administrator-2": "Administrator doesn't like Wang Bingbing", "user-1": "User likes Wang Bingbing", "user-2": "The user doesn't like Wang Bingbing", }; // Optimized function π const myFunction = (right, status) => { console.log(actionsObj[`${right}-${status}`]); }; // You can use the function as "value". The following cases are similar and will not be described in detail. const actionsObj = { "administrator-1": () => console.log("Administrator likes Wang Bingbing"), "administrator-2": () => console.log("Administrator likes Wang Bingbing"), "user-1": () => console.log("Administrator likes Wang Bingbing"), "user-2": () => console.log("Administrator likes Wang Bingbing"), }; // Optimized function π const myFunction = (right, status) => { actionsObj[`${right}-${status}`](); }; // Optimize "Examples with duplicate situations π°" // Public functions can be extracted. The following situations are similar and will not be repeated π const actions = () => { const f1 = () => console.log("Administrator likes Wang Bingbing"); const f2 = () => console.log("User likes Wang Bingbing"); return { "administrator-1": f1, "administrator-2": f1, "user-1": f2, "user-2": f2, }; }; // Optimized function π const myFunction = (right, status) => { actions()[`${right}-${status}`](); }; 2.3 Put the judgment conditions into a string and put it into the MapSimilarly, we can also use Map objects. We store the two conditions as strings. // Optimize "Example π°" //Put the judgment conditions into the Map const actionsMap = new Map([ ['administrator-1', 'Administrator likes Wang Bingbing'], ['administrator-2', 'The administrator doesn't like Wang Bingbing'], ['user-1', 'User likes Wang Bingbing'], ['user-2', 'The user doesn't like Wang Bingbing'] ]); // Optimized function π const myFunction = (right, status) => { console.log(actionsMap.get(`${right}-${status}`)); }; 2.4 Put the judgment condition into Object and then into Map// Optimize "Example π°" //Put the judgment conditions into the Map const actionsMap = new Map([ [{ right: 'administrator', status: 1 }, () => console.log('Administrator likes Wang Bingbing')], [{ right: 'administrator', status: 2 }, () => console.log('Administrator doesn't like Wang Bingbing')], [{ right: 'user', status: 1 }, () => console.log('User likes Wang Bingbing')], [{ right: 'user', status: 2 }, () => console.log('The user doesn't like Wang Bingbing')] ]); // Optimized function π const myFunction = (right, status) => { const action = [...actionsMap].filter(([e]) => (e.right === right && e.status === status)); action.forEach(([_, index]) => index.call()); }; 2.5 Write the judgment condition as a regular expression and then put it into the MapRegular expressions can be used to handle relatively complex situations. // Optimize "Examples with duplicate situations π°" // Write the judgment condition as a regular expression and then put it into the Map const actions = () => { const f1 = () => console.log('The administrator likes Wang Bingbing'); const f2 = () => console.log('User likes Wang Bingbing'); return new Map([ [/^administrator-[1-2]/, f1], [/^user-[1-2]/, f2] ]); }; // Optimized function π const myFunction = (right, status) => { const action = [...actions()].filter(([e]) => e.test(`${right}-${status}`)); action.forEach(([_, index]) => index.call()); }; ConclusionWe use native Object and Map objects to optimize the judgment, but in the actual development process, we still have to follow the principle of practicality first and avoid over-optimization. This is the end of this article about the elegant way to write judgments in JavaScript. For more information about the elegant way to write JavaScript judgments, please search for previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope you will support 123WORDPRESS.COM in the future! You may also be interested in:
|
<<: HTML table tag tutorial (8): background image attribute BACKGROUND
>>: Nginx handles http request implementation process analysis
Table of contents Build Vuex environment Summariz...
We often use click events in the a tag: 1. a href=...
WeChat applet uses scroll-view to achieve left-ri...
This article shares with you how to install Kylin...
Because the company asked me to build a WebServic...
I just happened to encounter this small requireme...
background Recently, some friends who are new to ...
Optimizing and refining information is always the ...
Using flex layout, if it is a nine-square grid, i...
Focus images are a way of presenting content that ...
Installation & Configuration The official web...
The meta tag is used to define file information an...
Preface The CentOS environment variable configura...
<br />Information duplication, information o...
Table of contents 1. Comments on MySQL primary ke...