How to optimize logic judgment code in JavaScript

How to optimize logic judgment code in JavaScript

Preface

The logical judgment statements we use in daily life include if...else..., switch...case..., do...while..., etc.

In simple scenarios, we may not feel the performance of these syntaxes, but when encountering complex business scenarios, if not handled properly, there will be a lot of logical nesting, poor readability and difficulty in expansion.

A journey of a thousand miles begins with a single step. To write highly maintainable and high-quality code, we need to start with the details. Today we will mainly discuss how to optimize logical judgment code in JavaScript.

Nesting level optimization

function supply(fruit, quantity) {
    const redFruits = ['apple', 'strawberry', 'cherry', 'cranberries'];
    // Condition 1: Fruit existsif (fruit) {
        // Condition 2: It is red fruit if (redFruits.includes(fruit)) {
            console.log('red fruit');
            // Condition 3: The number of fruits is greater than 10 if (quantity > 10) {
                console.log('The number is greater than 10');
            }
        }
    } else {
        throw new Error('There is no fruit!');
    }
}

From the above example, we can see that the judgment process is standard and consistent with the mapping of the real world. However, the code is nested, making it difficult to read and maintain.

If the fruit parameter is passed in, each execution will require at least two steps of if judgment, which will also cause performance problems.

Let's optimize the above code:

function supply(fruit, quantity) {
    const redFruits = ['apple', 'strawberry', 'cherry', 'cranberries'];
    if (!fruit) throw new Error('There is no fruit'); // Condition 1: When fruit is invalid, handle the error in advance if (!redFruits.includes(fruit)) return; // Condition 2: When it is not red fruit, return in advance

    console.log('red fruit');

    // Condition 3: The number of fruits is greater than 10 if (quantity > 10) {
        console.log('The number is greater than 10');
    }
}

Here we mainly optimize the nesting level, terminate the unqualified conditions in advance, reduce the three-level nesting to one level, simplify the code result structure, and enhance readability.

Optimization of multiple conditional branches

I believe many of us are familiar with the following code, right? (Think about when you first started writing code)

function pick(color) {
    // Select fruit based on color if (color === 'red') {
        return ['apple', 'strawberry'];
    } else if (color === 'yellow') {
        return ['banana', 'pineapple'];
    } else if (color === 'purple') {
        return ['grape', 'plum'];
    } else {
        return [];
    }
}

We need to know a little principle: if else is more suitable for conditional interval judgment, while switch case is more suitable for branch judgment of specific enumeration values.

We use switch...case... to rewrite it:

function pick(color) {
    // Select fruit based on color switch (color) {
        case 'red':
            return ['apple', 'strawberry'];
        case 'yellow':
            return ['banana', 'pineapple'];
        case 'purple':
            return ['grape', 'plum'];
        default:
            return [];
    }
}

The optimized code looks neatly formatted and clear in thought, but it is still lengthy. Continue to optimize:

With the help of Object's {key: value} structure, we can enumerate all the cases in Object, and then use key as index to get the content directly through Object.key or Object[key]:

const fruitColor = {
    red: ['apple', 'strawberry'],
    yellow: ['banana', 'pineapple'],
    purple: ['grape', 'plum'],
}
function pick(color) {
    return fruitColor[color] || [];
}

Use the Map data structure, the real (key, value) key-value pair structure:

const fruitColor = new Map()
    .set('red', ['apple', 'strawberry'])
    .set('yellow', ['banana', 'pineapple'])
    .set('purple', ['grape', 'plum']);

function pick(color) {
    return fruitColor.get(color) || [];
}

After optimization, the code is simpler and easier to expand.

For better readability, you can also define the object in a more semantic way and then use Array.filter to achieve the same effect:

const fruits = [
    {name: 'apple', color: 'red'},
    {name: 'strawberry', color: 'red'},
    {name: 'banana', color: 'yellow'},
    {name: 'pineapple', color: 'yellow'},
    {name: 'grape', color: 'purple'},
    {name: 'plum', color: 'purple'}
];

function pick(color) {
    return fruits.filter(f => f.color == color);
}

Summarize

The examples and methods used above are relatively elementary, but the ideas contained therein are worth our careful consideration. I hope everyone can gain something from them!

This is the end of this article about how to optimize logic judgment code in JavaScript. For more relevant JavaScript optimization logic judgment code content, please search for previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope everyone will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Introduction to logical judgment operators &&, || and ! in JavaScript
  • js logical judgment on IP address, subnet mask and gateway
  • A general discussion on JS logical judgment selectors || &&
  • JS logic judgment should not only use if-else and switch condition judgment (tips)

<<:  MySQL 8.0.13 manual installation tutorial

>>:  Ubuntu installs scrcpy to complete mobile phone screen projection and control (another way to use QQ WeChat in Ubuntu)

Recommend

A detailed introduction to the use of block comments in HTML

Common comments in HTML: <!--XXXXXXXX-->, wh...

Vue Beginner's Guide: Creating the First Vue-cli Scaffolding Program

1. Vue--The first vue-cli program The development...

Specific use of Linux gcc command

01. Command Overview The gcc command uses the C/C...

An in-depth introduction to React refs

1. What is Refs is called Resilient File System (...

MySQL data type details

Table of contents 1. Numeric Type 1.1 Classificat...

Detailed explanation of putting common nginx commands into shell scripts

1. Create a folder to store nginx shell scripts /...

Building .NET Core 2.0 + Nginx + Supervisor environment under Centos7 system

1. Introduction to Linux .NET Core Microsoft has ...

Vue3.0+vite2 implements dynamic asynchronous component lazy loading

Table of contents Create a Vite project Creating ...

Apache Bench stress testing tool implementation principle and usage analysis

1: Throughput (Requests per second) A quantitativ...

Summary of MySQL InnoDB locks

Table of contents 1. Shared and Exclusive Locks 2...

Detailed explanation of MySQL sql_mode query and setting

1. Execute SQL to view select @@session.sql_mode;...

How to visualize sketched charts in Vue.js using RoughViz

introduce A chart is a graphical representation o...