[Front-end dictionary] From returnWeekday() on if() statement code optimization

Preface

Recently, the department is doing some optimizations on the previous code. I saw a series of if(){}elseif(){} logic judgments in the code. This obviously has room for optimization.

Since the internal code is not suitable for sharing, I will use <output today as the day of the week> to talk about some solutions for logical judgment optimization.

Here is a statement first to avoid any doubts:

What we use in the project is likely to have multiple levels of nesting, unlike my example, which has only one level. However, the optimization idea is roughly the same. Because the returnWeekday() method is exceptionally simple, declare it in advance.
demand

Write a returnWeekday() method to return "Today is week*".

Next we will take it step by step.

optimization process

Here I simply divide it into "beginner -> entry -> intermediate" these stages.

Beginner

When we started to get the requirements and saw a series of logical judgments, the first thing that came to mind should be the if statement.

code show as below:

function returnWeekday(){

    let string = "今天是星期";

    let date = new Date().getDay();

    if (date === 0) {

        string += "日";

    } else if (date === 1) {

        string += "一";

    } else if (date === 2) {

        string += "二";

    } else if (date === 3) {

        string += "三";

    } else if (date === 4) {

        string += "四";

    } else if (date === 5) {

        string += "五";

    } else if (date === 6) {

        string += "六";

    }

    return string

}

console.log(returnWeekday())

When we finish writing such code, the first impression is whether there are too many elseif blocks.

But while we are still thinking about how to optimize, the product will send you a message on Dingding to ask how this requirement is completed? He also brought a smirk emoji package. At this time you tell yourself, let's talk about this optimization later. But over time, demand is added. This is never optimized again until the next one takes over.

The above code does have too many elseif blocks, which makes it uncomfortable to look at.

When we were watching "JavaScript Advanced Programming", we saw this sentence:

The switch statement is most closely related to the if statement, and it is also a flow control statement commonly used in other languages.

So can we consider using the switch statement to optimize it?

getting Started

Here we use the switch statement to optimize the code.

Note: The switch statement uses the congruent operator when comparing values, and there will be no type conversion.

code show as below:

function returnWeekday(){

    let string = "今天是星期";

    let date = new Date().getDay();

    switch (date) {

        case 0 :

            string += "日";

            break;

        case 1 :

            string += "一";

            break;

        case 2 :

            string += "二";

            break;

        case 3 :

            string += "三";

            break;

        case 4 :

            string += "四";

            break;

        case 5 :

            string += "五";

            break;

        case 6 :

            string += "六";

            break;

    }

    return string

}

console.log(returnWeekday())

We concatenate characters in the case to achieve the purpose of outputting the expected result. The structure here does look a little clearer than the if statement. But still a little confused?

Suppose one day, the relevant organization discovers that the horoscope has changed. It needs to be eight days a week (product thinking, you can’t imagine). Our returnWeekday() method needs an extra layer of judgment.

Our hope is that the encapsulated method should not be modified frequently. But changes in demand are beyond your control.

So we continue to think about how to optimize.

intermediate

We see that the case here is a number, which is consistent with the subscript of the array.

That is: ['天','one','two','three','four','five','six'] subscripts.

So we can consider using arrays to optimize.

code show as below:

function returnWeekday(){

    let string = "今天是星期";

    let date = new Date().getDay();

    // 使用数组

    let dateArr = ['天','一','二','三','四','五','六'];

    return string + dateArr[date]

}

console.log(returnWeekday())

The above code is much clearer than the switch statement and if statement. And even if the week becomes eight days, just modify the dateArr array.

What if each of our cases is an irregular string? Then we use objects, each case is a key

code show as below:

function returnWeekday(){

    let string = "今天是星期";

    let date = new Date().getDay();

    // 使用对象

    dateObj = { 

        0: '天', 

        1: "一", 

        2: "二", 

        3: "三", 

        4: "四", 

        5: "五", 

        6: "六", 

    };

    return string + dateObj[date]

}

console.log(returnWeekday())

The above use of array or object writing improves the readability of the code and at the same time it becomes easier to maintain.

Use charAt character method

Strings have a similar method to using array subscripts:

// charAt 定位方法

function returnWeekday(){

    return "今天是星期" + "日一二三四五六".charAt(new Date().getDay());

}

console.log(returnWeekday())

Demand changes

At this time, some people hope that the returnWeekday() method not only returns the day of the week today, but also needs to distinguish between working days and rest days and call related methods.

If you use switch, if, or array, it is a bit troublesome to maintain, and there are many places to rewrite.

function returnWeekday(){

    let string = "今天是星期";

    let date = new Date().getDay();

    // 使用对象

    dateObj = { 

        0: ['天','休'], 

        1: ["一",'工'], 

        2: ["二",'工'], 

        3: ["三",'工'], 

        4: ["四",'工'], 

        5: ["五",'工'], 

        6: ["六",'休'], 

    }

    // 类型,这里也可以对应相关方法

    dayType = {

        '休': function(){

            // some code

            console.log('为休息日')

        },

        '工': function(){

            // some code

            console.log('为工作日')

        }

    }

    let returnData = {

        'string' : string + dateObj[date][0],

        'method' : dayType[dateObj[date][1]]

    }

    return returnData

};

console.log(returnWeekday().method.call(this))

Other common optimization methods

Here are some common optimization methods.

Ternary operation

Suitable for simple if(){}else{} situations.

//滚动监听,头部固定

handleScroll: function () {

    let offsetTop = this.$refs.pride_tab_fixed.getBoundingClientRect().top;

    if( offsetTop < 0 ){

        this.titleFixed = true

    } else {

        this.titleFixed = false

    }

    // 改成三元

    (offsetTop < 0) ? this.titleFixed = true : this.titleFixed = false;

    // 我们发现条件块里面的赋值情况是布尔值,所以可以更简单

    this.titleFixed = offsetTop < 0;

}

In this way, the readability is not reduced when the code is streamlined.

Logical AND operator

Sometimes we can use the logical AND operator to simplify the code

if( falg ){

    someMethod()

}

Can be changed to:

falg && someMethod();

Use includes to handle multiple conditions

if( code === '202' || code === '203' || code === '204' ){

    someMethod()

}

Can be changed to

if( ['202','203','204'].includes(code) ){

    someMethod()

}

Vue related articles output plan

Recently, friends always ask me questions related to Vue, so I will output 10 Vue-related articles next, hoping to be helpful to everyone. I will keep an update in 7 to 10 days.

  1. The process of injecting Vuex into the Vue life cycle (completed)

  2. The necessary knowledge reserve for learning Vue source code (completed)

  3. Analysis of Vue Responsive Principle (Completed)

  4. The process of patching new and old VNodes

  5. How to develop functional components and upload npm

  6. Optimize your Vue project from these aspects

  7. Talking about front-end routing development from Vue-Router design

  8. How to use Webpack correctly in the project

  9. Vue server rendering

  10. How to choose between Axios and Fetch

I suggest you pay attention to my official account, you can receive the latest articles as soon as possible.

[Front-end dictionary] From returnWeekday() on if() statement code optimization

If you want to join the group exchange, you can scan the code to join the group yourself:

Guess you like

Origin blog.51cto.com/15077552/2596422
Recommended