11 Javascript tips to help you improve the quality of the code, dry goods collection!

Javascript common code optimization and reconstruction methods

Introduction

Mainly introduce the following points:

  1. Refinement function

  2. Combine repeated conditional fragments

  3. Distill conditional branch statements into functions

  4. Reasonable use of loops

  5. Let the function exit in advance instead of nested conditional branches

  6. Pass object parameters instead of long parameter lists

  7. Use less ternary operators

  8. Reasonable use of chain calls

  9. Break down large classes

  10. Conjugation bit

  11. Pure function

  12. Compile a complete PDF of the Java Interview Collection

This article will be updated continuously, and welcome to add deficiencies.

1. Refine function

benefit:

  • Avoid large functions.

  • Independent functions help code reuse.

  • Independent functions are easier to overwrite.

  • If an independent function has a good name, it itself serves as a comment.

  • Semanticization puts multiple sections of separated logic in different functions, which can make the code logic clear and clearly see what is being done at each step.

Code example:

Realize to get data, then manipulate dom to display data, and finally add events

  • Before function refinement
// 逻辑都写在一起,需要将所有逻辑看完才知道这段代码是干嘛的,局部逻辑无法复用
function main() {
    $.ajax.get('/getData').then((res) => {
        const ul = document.getElementById('ul');
        ul.innerHTML = res.list.map(text => `<li class="li">${text}</li>`).join('\n');
        const list = document.getElementsByClassName('li');
        for (let i = 0; i < list.length; i ++) {
            list[i].addEventListener('focus', () => {
                // do something
            });
        }
    });
}
  • After the function is refined
function getData() {
    return $.ajax.get('/getData').then((res) => res.data.list);
}
function showList(list) {
    const ul = document.getElementById('ul');
    ul.innerHTML = list.map(text => `<li class="li">${text}</li>`).join('\n');
}
function addEvent() {
    const list = document.getElementsByClassName('li');
    for (let i = 0; i < list.length; i ++) {
        list[i].addEventListener('focus', () => {
            // do something
        });
    }
}
// 逻辑清晰,一眼读懂每一步在做什么,某些提炼出来的函数还可以被复用
async function main() {
    const list = await getData(); // 获取数据
    showList(list); // 显示页面
    addEvent(); // 添加事件
}

2. Combine repeated conditional fragments

If there are some conditional branch statements in a function body, and some repetitive code is scattered inside these conditional branch statements, then it is necessary to merge and remove duplicates.

// 合并前
function main( currPage ){
    if ( currPage <= 0 ){
        currPage = 0;
        jump( currPage ); // 跳转
    }else if ( currPage >= totalPage ){
        currPage = totalPage;
        jump( currPage ); // 跳转
    }else{
        jump( currPage ); // 跳转
    }
};

// 合并后
function main( currPage ){
    if ( currPage <= 0 ){
        currPage = 0;
    }else if ( currPage >= totalPage ){
        currPage = totalPage;
    }
    jump( currPage ); // 把jump 函数独立出来
};

3. Refine conditional branch statements into functions

Complicated conditional branch statements are an important reason why the program is difficult to read and understand, and it can easily lead to a huge function. Sometimes the conditional branch statement can be refined into semantic functions to make the code more intuitive and logically clear.

// 根据不同季节决定打折力度
function getPrice( price ){
    var date = new Date();
    if ( date.getMonth() >= 6 && date.getMonth() <= 9 ){ // 夏天
        return price * 0.8;
    }
    return price;
};

// 是否是夏天
function isSummer(){
    var date = new Date();
    return date.getMonth() >= 6 && date.getMonth() <= 9;
};
// 提炼条件后
function getPrice( price ){
    if ( isSummer() ){
        return price * 0.8;
    }
    return price;
};

4. Reasonable use of loops

If multiple pieces of code are actually responsible for some repetitive work, then loops can be used instead to make the amount of code less.

// 判断是什么浏览器
function getBrowser(){
    const str = navigator.userAgent;
    if (str.includes('QQBrowser')) {
 return 'qq';
    } else if (str.includes('Chrome')) {
 return 'chrome';
    } else if (str.includes('Safari')) {
        return 'safri';
    } else if (str.includes('Firefox')) {
        return 'firefox';
    } else if(explorer.indexOf('Opera') >= 0){
        return 'opera';
    } else if (str.includes('msie')) {
        return 'ie';
    } else {
        return 'other';
    }
};

// 循环判断,将对应关系抽象为配置,更加清晰明确
function getBrowser(){
    const str = navigator.userAgent;
    const list = [
        {key: 'QQBrowser', browser: 'qq'},
        {key: 'Chrome', browser: 'chrome'},
        {key: 'Safari', browser: 'safari'},
        {key: 'Firefox', browser: 'firefox'},
        {key: 'Opera', browser: 'opera'},
        {key: 'msie', browser: 'ie'},
    ];
    for (let i = 0; i < list.length; i++) {
        const item = list[i];
        if (str.includes(item.key)) {return item.browser};
    }
    return 'other';
}

5. Let the function exit in advance instead of nested conditional branches

Let the function 多出口return early and replace 嵌套条件分支.

function del( obj ){
    var ret;
    if ( !obj.isReadOnly ){ // 不为只读的才能被删除
        if ( obj.isFolder ){ // 如果是文件夹
            ret = deleteFolder( obj );
        }else if ( obj.isFile ){ // 如果是文件
            ret = deleteFile( obj );
        }
    }
    return ret;
};

function del( obj ){
    if ( obj.isReadOnly ){ // 反转if 表达式
        return;
    }
    if ( obj.isFolder ){
        return deleteFolder( obj );
    }
    if ( obj.isFile ){
        return deleteFile( obj );
    }
};

6. Pass object parameters instead of long parameter lists

Function parameters are too long to increase the risk of errors. It is troublesome to ensure that the order of transmission is correct, and the readability of the code will also deteriorate. Try to ensure that the function parameters are not too long. If you must pass multiple parameters, it is recommended to use 对象instead.

Generally speaking, function parameters are best不要超过3个

function setUserInfo( id, name, address, sex, mobile, qq ){
    console.log( 'id= ' + id );
    console.log( 'name= ' +name );
    console.log( 'address= ' + address );
    console.log( 'sex= ' + sex );
    console.log( 'mobile= ' + mobile );
    console.log( 'qq= ' + qq );
};
setUserInfo( 1314, 'sven', 'shenzhen', 'male', '137********', 377876679 );

function setUserInfo( obj ){
    console.log( 'id= ' + obj.id );
    console.log( 'name= ' + obj.name );
    console.log( 'address= ' + obj.address );
    console.log( 'sex= ' + obj.sex );
    console.log( 'mobile= ' + obj.mobile );
    console.log( 'qq= ' + obj.qq );
};
setUserInfo({
    id: 1314,
    name: 'sven',
    address: 'shenzhen',
    sex: 'male',
    mobile: '137********',
    qq: 377876679
});

7. Use less ternary operators

The ternary operator has high performance and less code.

But the ternary operator should not be abused. We should use it in simple logic branches and avoid it in complex logic branches.

// 简单逻辑可以使用三目运算符
var global = typeof window !== "undefined" ? window : this;

// 复杂逻辑不适合使用
var ok = isString ? (isTooLang ? 2 : (isTooShort ? 1 : 0)) : -1;

8. Reasonable use of chain calls

Advantages: The  chain call is simple to use, and the amount of code is small.

Disadvantages: The disadvantage of  chain call is 调试不方便that if we know that there is an error in a chain, we must first disassemble the chain before adding some debugging logs or adding breakpoints, so that we can locate the place where the error occurs.

If the structure of the chain is relatively stable and it is not easy to be modified later, the chain type can be used.

var User = {
    id: null,
    name: null,
    setId: function( id ){
        this.id = id;
        return this;
    },
    setName: function( name ){
        this.name = name;
        return this;
    }
};
User
  .setId( 1314 )
  .setName( 'sven' );

var user = new User();
user.setId( 1314 );
user.setName( 'sven' );

9. Break down large classes

The decomposition of a large class is very similar to the refinement of a function. If the class is too large, the logic will be unclear and difficult to understand and maintain.

Reasonable decomposition of large classes can make the logic of the class clear, and the sub-modules can be reused conveniently.

10. Conjugation bit

The performance of programming language calculation of multiplication and division is not high, but in some cases the use of bit operators can improve the performance of operations such as multiplication and division.

11. Pure functions

A pure function refers to a function that does not 依赖于and the 不改变state of variables outside its scope.

The return value of a pure function is only determined by the parameters when it is called, and its execution does not depend on the state of the system (execution context).

The same input parameters will definitely get the same output, that is, there are no internal random variables that will affect the output .

Features that are not pure functions:

  • Change the file system

  • Insert records into the database

  • Send an http request

  • Variable data

  • Print/log

  • Get user input

  • DOM query

  • Access system status

The role of pure functions:

  • Reliability : The function return is always consistent with expectations

  • Cacheability : As long as the input is the same, the output must be the same, so the input can be used as the key and the output as the value, and the calculated result can be cached using the object

  • Portability : Because there is no external dependency, it can run correctly when transplanted to any environment

  • Testability : Convenient for unit testing of functions

  • Parallelism : For some complex calculations, it can be calculated in parallel (for example, using nodejs multiple child processes to calculate multiple tasks in parallel at the same time to improve the calculation speed)

Application scenarios:

var a = 1;
// 非纯函数
function sum(b) {
    return a + b;
}
// 非纯函数
function sum(b) {
    a = 2;
    return b;
}
// 非纯函数
function sum(b) {
    return b + Math.random();
}

// 纯函数
function sum (b, c) {
    return b + c;
}

Guess you like

Origin blog.51cto.com/14975073/2597298