Home  >  Article  >  Web Front-end  >  One article teaches you how to implement JavaScript if branch optimization

One article teaches you how to implement JavaScript if branch optimization

青灯夜游
青灯夜游forward
2023-03-14 19:37:131968browse

1000 judgment conditions require writing 1000 ifs? How to optimize if branch statement? The following article will talk to you about how to achieve branch optimization. I hope it will be helpful to everyone!

One article teaches you how to implement JavaScript if branch optimization

I recently saw this piece of code while surfing the Internet:

function getUserDescribe(name) {
    if (name === "小刘") {
        console.log("刘哥哥");
    } else if (name === "小红") {
        console.log("小红妹妹");
    } else if (name === "陈龙") {
        console.log("大师");
    } else if (name === "李龙") {
        console.log("师傅");
    } else if (name === "大鹏") {
        console.log("恶人");
    } else {
        console.log("此人比较神秘!");
    }
}

At first glance, I didn’t feel anything unusual, but if there are 1000 judgment conditions, Is it difficult to write 1,000 if branches according to this way of writing?

If you write a large number of if branches, and may also have branches within branches, you can imagine that the readability and maintainability of the entire code will be greatly reduced. This is indeed a headache in actual development. Is there any way to achieve the requirements while avoiding these problems? [Recommended learning: javascript video tutorial]

1️⃣ Simple branch optimization

This involves branch optimization, let Let’s change our thinking and optimize the above code structure:

function getUserDescribe(name) {
    const describeForNameMap = {
        小刘: () => console.log("刘哥哥"),
        小红: () => console.log("小红妹妹"),
        陈龙: () => console.log("大师"),
        李龙: () => console.log("师傅"),
        大鹏: () => console.log("恶人"),
    };
    describeForNameMap[name] ? describeForNameMap[name]() : console.log("此人比较神秘!");
}

The judgments in the problem code are all simple Equal judgment, then we can write these judgment conditions as an attribute In the object describeForNameMap, the values ​​corresponding to these attributes are the processing functions after the conditions are established.

After that, we only need to obtain the corresponding value in the describeForNameMap object through the parameters received by the getUserDescribe function. If the value exists, run the value (because the value is a function).

In this way, the original if branch judgment is converted into a simple key value corresponding value. The conditions and processing functions correspond one to one, making it clear at a glance.

2️⃣ Complex branch optimization

Then if the judgment condition in our if branch is not just a simple equality judgment, but also has some calculations that need to be calculated What should we do when the expression is ? (As shown below)

function getUserDescribe(name) {
    if (name.length > 3) {
        console.log("名字太长");
    } else if (name.length < 2) {
        console.log("名字太短");
    } else if (name[0] === "陈") {
        console.log("小陈");
    } else if (name[0] === "李" && name !== "李鹏") {
        console.log("小李");
    } else if (name === "李鹏") {
        console.log("管理员");
    } else {
        console.log("此人比较神秘!");
    }
}

For code with this structure, objects cannot be introduced for branch optimization. We can introduce two-dimensional arrays for branch optimization:

function getUserDescribe(name) {
    const describeForNameMap = [
        [
            (name) => name.length > 3, // 判断条件
            () => console.log("名字太长") // 执行函数
        ],
        [
            (name) => name.length < 2, 
            () => console.log("名字太短")
        ],
        [
            (name) => name[0] === "陈", 
            () => console.log("小陈")
        ],
        [
            (name) => name === "大鹏", 
            () => console.log("管理员")
        ],
        [
            (name) => name[0] === "李" && name !== "李鹏",
            () => console.log("小李"),
        ],
    ];
    // 获取符合条件的子数组
    const getDescribe = describeForNameMap.find((item) => item[0](name));
    // 子数组存在则运行子数组中的第二个元素(执行函数)
    getDescribe ? getDescribe[1]() : console.log("此人比较神秘!");
}

Above we defined an describeForNameMap array. Each element in the array represents a set of judgment conditions and execution functions (also an array). Then we use the find method of the array. Just find the subarray in the describeForNameMap array that meets the judgment conditions.

3️⃣ Detach branch

The describeForNameMap object we defined in the above example is an independent structure, and we can completely detach it Go out:

const describeForNameMap = {
    小刘: () => console.log("刘哥哥"),
    小红: () => console.log("小红妹妹"),
    陈龙: () => console.log("大师"),
    李龙: () => console.log("师傅"),
    大鹏: () => console.log("恶人"),
};

function getUserDescribe(name) {
    describeForNameMap[name] ? describeForNameMap[name]() : console.log("此人比较神秘!");
}
const describeForNameMap = [
    [
        (name) => name.length > 3, // 判断条件
        () => console.log("名字太长") // 执行函数
    ],
    [
        (name) => name.length < 2, 
        () => console.log("名字太短")
    ],
    [
        (name) => name[0] === "陈", 
        () => console.log("小陈")
    ],
    [
        (name) => name === "大鹏", 
        () => console.log("管理员")
    ],
    [
        (name) => name[0] === "李" && name !== "李鹏",
        () => console.log("小李"),
    ],
];
    
function getUserDescribe(name) {
    // 获取符合条件的子数组
    const getDescribe = describeForNameMap.find((item) => item[0](name));
    // 子数组存在则运行子数组中的第二个元素(执行函数)
    getDescribe ? getDescribe[1]() : console.log("此人比较神秘!");
}

Through modular development, you can also write this map object into a separate js file, and then import it wherever you need to use it. That’s it.

4️⃣ Controversy

In this way, the entire getUserDescribe function becomes very concise. Some students may ask what’s the point of this? What to use? Isn't this more troublesome? If if else really doesn’t look good, then I will use if return instead of else:

function getUserDescribe(name) {
    if (name === "小刘") {
        console.log("刘哥哥");
        return;
    }
    if (name === "小红") {
        console.log("小红妹妹");
        return;
    }
    if (name === "陈龙") {
        console.log("大师");
        return;
    }
    if (name === "李龙") {
        console.log("师傅");
        return;
    }
    if (name === "大鹏") {
        console.log("恶人");
        return;
    }
    console.log("此人比较神秘!");
}

Just imagine, if There are 1000 judgment branches in your getUserDescribe function, and there are also a large number of processing codes that are executed based on the judgment results, and the getUserDescribe function will return the value of this processed judgment result.

At this time, the focus of the getUserDescribe function lies in the processing of the judgment result, not in which branch the result is obtained, for example :

function getUserDescribe(name) {
    let str; // 存储判断结果
    if (name.length > 3) {
        str = "名字太长";
    } else if (name.length < 2) {
        str = "名字太短";
    } else if (name[0] === "陈") {
        str = "小陈";
    } else if (name[0] === "李" && name !== "李鹏") {
        str = "小李";
    } else if (name === "李鹏") {
        str = "管理员";
    } else {
        str = "此人比较神秘!";
    }
    // 对判断结果str的一些处理
    // ......
    console.log(str);
    return str;
}

If you do not perform branch optimization, the

getUserDescribe function will be occupied by a large number of if branches, making the getUserDescribe function the focus of Lost (getUserDescribeFunctionThe focus is on the processing of the judgment result, not on which branch the result is obtained through), then you can take a look at our optimized code:

const describeForNameMap = [
    [(name) => name.length > 3, () => "名字太长"],
    [(name) => name.length < 2, () => "名字太短"],
    [(name) => name[0] === "陈", () => "小陈"],
    [(name) => name === "大鹏", () => "管理员"],
    [(name) => name[0] === "李" && name !== "李鹏", () => "小李"],
];

function getUserDescribe(name) {
    let str; // 存储判断结果
    const getDescribe = describeForNameMap.find((item) => item[0](name));
    if (getDescribe) {
        str = getDescribe[1]();
    } else {
        str = "此人比较神秘!";
    }
    // 对判断结果str的一些处理
    // ......
    console.log(str);
    return str;
}

Looking at the optimized

getUserDescribe function we can know that it obtains a value from describeForNameMap and assigns it to str (describeForNameMap We don't care how returns the value), and then did some processing on str. This highlights the focus of the getUserDescribe function (processing the judgment result str).

In this example

describeForNameMapThe second element of the subarray can directly use a value:[(name) => name.length > 3 , "Name is too long"], but for the scalability of the overall code, it is recommended to use functions, because functions can receive parameters, making it easier to deal with more complex scenarios in the future.

? Conclusion

Branch optimizationThere are different implementation methods and application scenarios in various languages. This article uses JavaScript Introduces two ideas of code branch optimization. The implementation of the code is very simple, and the focus is on the application of this idea.

In fact, there has been controversy about the issue of branch optimization. There are currently two views:

  • View 1: There is no need to bother optimizing it, and optimizing it Because the following code creates an extra object/array, retrieving the object/array is still more wasteful than simply if else.
  • Viewpoint 2: The code after branch optimizationreadability/maintainability is better, and the introduction of object/array brings Performance issues are simply not worth mentioning in this day and age.

What is your opinion?

For more programming-related knowledge, please visit: Programming Teaching! !

The above is the detailed content of One article teaches you how to implement JavaScript if branch optimization. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:juejin.cn. If there is any infringement, please contact admin@php.cn delete