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

One article teaches you how to implement branch optimization in JavaScript

WBOY
WBOYforward
2022-11-15 17:00:571692browse

This article brings you relevant knowledge about JavaScript, which mainly introduces the relevant content about branch optimization. If there are many judgment conditions, using a large number of if branches will make the entire code The readability and maintainability are greatly reduced. Let's take a look at it. I hope it will be helpful to everyone.

One article teaches you how to implement branch optimization in JavaScript

【Related recommendations: JavaScript video tutorial, web front-end

Watched it recently while surfing the Internet Here is a piece of code like this:

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 don’t feel anything unusual, but if there are 1,000 judgment conditions, is it difficult to write 1,000 if branches in this way?

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?

Simple branch optimization

This involves branch optimization, let us 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 Equality judgments, then we can write these judgment conditions as an attribute into the object describeForNameMap. These attributes correspond to The value is the processing function after the condition is 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.

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 expression, what should we do? (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.

Extraction branch

The describeForNameMap object we defined in the above example is an independent structure, and we can completely extract it. :

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. Can.

Controversy

In this way, the entire getUserDescribe function becomes very concise. Some students may ask what is the use of this? Woolen cloth? 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 exampledescribeForNameMapThe second element of the subarray can directly use a value:[(name) => name.length > 3, "name 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 adoptsJavaScript 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/maintainabilityis better, and the introduction of object/array brings Performance issues are simply not worth mentioning in this day and age.

[Related recommendations: JavaScript video tutorial, web front-end]

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

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