An example of elegant writing of judgment in JavaScript

An example of elegant writing of judgment in JavaScript

Preface

When 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 Example

We 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 Object

We 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 Map

In 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 example

Since 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 Object

Both 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 Map

Similarly, 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 Map

Regular 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());
};

Conclusion

We 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:
  • Detailed explanation of Javascript basics loop
  • How to use async and await correctly in JS loops
  • Four data type judgment methods in JS
  • About the difference between js typeof and instanceof in judging data types and their development and use
  • How to convert a string into a number in JavaScript
  • parseInt parseFloat js string conversion number
  • JavaScript common statements loop, judgment, string to number

<<:  HTML table tag tutorial (8): background image attribute BACKGROUND

>>:  Nginx handles http request implementation process analysis

Recommend

Detailed explanation of Vuex environment

Table of contents Build Vuex environment Summariz...

Several methods of calling js in a are sorted out and recommended for use

We often use click events in the a tag: 1. a href=...

WeChat applet scroll-view realizes left-right linkage effect

WeChat applet uses scroll-view to achieve left-ri...

VMware Workstation Installation (Linux Kernel) Kylin Graphic Tutorial

This article shares with you how to install Kylin...

How to install nginx on win10

Because the company asked me to build a WebServic...

Thoughts on truncation of multi-line text with a "show more" button

I just happened to encounter this small requireme...

How to implement Docker to dynamically pass parameters to Springboot projects

background Recently, some friends who are new to ...

Some conclusions on the design of portal website focus pictures

Focus images are a way of presenting content that ...

Tutorial on building a zookeeper server on Windows

Installation & Configuration The official web...

Simple comparison of meta tags in html

The meta tag is used to define file information an...

In-depth explanation of environment variables and configuration files in CentOS

Preface The CentOS environment variable configura...

Web2.0: Causes and Solutions of Information Overload

<br />Information duplication, information o...

Detailed explanation of primary keys and transactions in MySQL

Table of contents 1. Comments on MySQL primary ke...