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

Introduction to Nginx regular expression related parameters and rules

Preface Recently, I have been helping clients con...

HTML table tag tutorial (23): row border color attribute BORDERCOLORDARK

In rows, dark border colors can be defined indivi...

The "3I" Standards for Successful Print Advertising

For many domestic advertisers, the creation and ev...

Example code of how CSS matches multiple classes

CSS matches multiple classes The following HTML t...

How to use mysql to complete the data generation in excel

Excel is the most commonly used tool for data ana...

How to install MySQL using yum on Centos7 and achieve remote connection

Centos7 uses yum to install MySQL and how to achi...

The whole process of IDEA integrating docker to deploy springboot project

Table of contents 1. IDEA downloads the docker pl...

MySQL GTID comprehensive summary

Table of contents 01 Introduction to GTID 02 How ...

Summary of how to add root permissions to users in Linux

1. Add a user . First, use the adduser command to...

Detailed steps to install Anaconda on Linux (Ubuntu 18.04)

Anaconda is the most popular python data science ...

Implementation of Nginx hot deployment

Table of contents Semaphore Nginx hot deployment ...

Solution to the problem of MySQL data delay jump

Today we analyzed another typical problem about d...

Detailed explanation of JavaScript function introduction

Table of contents Function Introduction function ...

A permanent solution to MYSQL's inability to recognize Chinese

In most cases, MySQL does not support Chinese whe...

JavaScript Basics: Scope

Table of contents Scope Global Scope Function Sco...