How to write good JavaScript is certainly a problem that every front-end engineer has been thinking about. Moon Shadow teacher tells us some principles of writing good JavaScript, and also teaches us some skills of how to write good JavaScript. Today, continue to learn JavaScript with Moon Shadow teacher ~~

What should we focus on when we’re writing code?

Programs are written for people to read, and only occasionally for computers to execute. — Donald Ervin Knuth, Gartner

Coding style is of course the most important concern in writing good code, followed by coding efficiency. (This is not certain ~ still depends on the use scenario)

Left – pad

Take a look back at the much-discussed left-pad incident of 2016

The image is from The Great Sage’s blog in 2016

There are many slots in the event itself

  • NPM module granularity
  • Code style.
  • Code quality/efficiency
function leftpad(str, len, ch){
    str = String(str);
    
    var i = -1;
    
    if(! ch && ch ! = =0) ch = "";
    
    len = len - str.length;
    
    while(++i < len){
        str = ch + str;
    }
    
    return str;
}
Copy the code

Moon shadow teacher said here this code he felt that the problem is not big, this is a good to understand the code.

First of all, there is the problem of NPM module granularity. Why does a function constitute a module? Is the granularity too fine? Now it’s too fine-grained, but back then it was fine.

Code style problem, the code to write a very readable, very simple code. Good code is itself a comment

And finally, the code efficiency, which is not very efficient, is O(N) time complexity, but in practice, we don’t actually have to spell a lot of characters, so it’s ok.

In summary, there is nothing wrong with this code

Let’s take a look at why so many people criticize it for being inefficient. What can be done to improve the efficiency of this code?

Let’s look at the loop part. If you repeat a string n times, do you really need n times to loop through the string step by step?

while(++i < len){
    str = ch + str;
}
Copy the code

For example, repeat the * 100 times

The binary of 100 is 1100100

The while loop is equivalent to adding the * 100 times in a row using the idea of decimal notation.

Using binary thinking, doubling each * (a power of two) only takes 7 cycles to complete, as shown in the following code

This is optimized code

function leftpad(str, len, ch=""){
    str = "" + str;

    const padLen = len - str.length;
    
    if(padLen <= 0) {return str;
    }else{
        return (""+ ch).repeat(padLen) + str; }}Copy the code

Here we use some of ES6’s features, default assignment, the string repeat method, how does it do n operations

The key code defined in its Ployfill implementation on MDN is as follows

var rpt = ""
for(;;) {if((count & 1) = =1) {
        rpt += str;
    }
    
    count >>>= 1;
    
    if(count == 0) {break;
    }
    
    str += str;
}
Copy the code

For quick power algorithm analysis, see my blog “Algorithms” for quick power operations using JavaScript

Let’s take a look at this code. Bits are used here: & and and >>> unsigned right shift

Count & 1 Takes the lowest binary value of count and checks whether it is the same as 1. If they are the same, 1 is returned; otherwise, 0 is returned

Count >>> 1 Moves the binary of count one bit to the right, removing the least significant bit

So what this code is saying is that it goes through the binary of count in reverse order, doubling STR each time, and spelling STR into RPT when it encounters a 1 bit

Repeat the above example 100 times * backwards through the binary of 100 1100100, doubling STR each time, adding the current STR to RPT when a 1 is encountered in the binary

This loops 7+1 times, and STR is 1* (0), 2* (0), 4* (1), 8* (0), 16* (0), 32* (1), 64* (1), so the final RPT is 4+32+64=100 *

So the time complexity here is order logN, and the number of cycles is the binary number of count

You can still optimize

var rpt = "";
do {
    rpt += str;
    str += str;
    count &= count - 1;
} while(count);
Copy the code

count &= count – 1; You can get rid of the last 1 in binary

1100100 -> 1100000 -> 1000000 -> 0000000

So the number of times we’re going to loop is the number of bits of one in the binary number of count for example, if 100 is 1100100, we’re going to loop three times

But this situation can not reach the result we want, it should be the teacher’s PPT mistake ~ or I misunderstood, if you know what the situation, can you leave a message or private message to teach me

Interestingly, however, the ployfill code given by MDN now uses something like a while loop 😂😂😂

while (count) {
   str += str;
   count--;
}
Copy the code

Make a long time efficiency and then go back ~~ ha ha

That said, in most cases, the need for efficiency is not so dire, so focusing on code style first is still an important skill for writing good JavaScript code!

Judgment identity matrix

Let’s look at the code below

This code seems to me to have a lot of problems

  1. It’s too long and not very readable
  2. The extensibility is not high
  3. Poor encapsulation

But this is real code

Because this is the most efficient way to do it under the current conditions, and this scenario requires efficiency first.

So in actual development, we still have to depend on the situation.

conclusion

Here we learned to use bit operations for fast exponents to reduce the number of loops and improve our code efficiency

But in reality, we should be more concerned with the readability of our code when the efficiency requirements are not so dire

Finally, style and efficiency need to be chosen according to the actual situation

More related posts

[Youth Training camp] Teacher Yue Ying told me the three principles of writing good JavaScript — each is responsible for his own work

[Youth Training Camp] Teacher Yue Ying told me the three principles of good JavaScript writing — component encapsulation

[Youth Training Camp] Teacher Yue Ying told me the three principles of good JavaScript – process abstraction

[Youth Training Camp] Teacher Yue Ying told me four skills to write good JavaScript — style first

[Youth Training Camp] Teacher Yue Ying told me four skills to write good JavaScript — make sure it is correct