This is the 21st day of my participation in the August More Text Challenge

We’ve already shared some tips and tricks on how to write JS well. This article will conclude with a look at what should be the most important thing to focus on when writing code. What writing is not desirable, can be improved.

preface

“Early review”

How heavy learn front-end | follow the shadow of JavaScript packaging components

Heavy learning process of front-end | follow moon JavaScript abstract +

Let’s start with a piece of code

Is the following code good? Why is that? (You can think about it for a second πŸ€”)

πŸ‘‡

πŸ‘‡

πŸ‘‡

πŸ‘‡

πŸ‘‡

πŸ‘‡

This is actually a piece of real code from the spriteJs framework, which you can look at on line 131

SpriteJs is a cross-terminal Canvas drawing framework open source by 360 Qiqi Dance Company. It can quickly draw structured UI, animation and interactive effects based on Canvas. It is a cross-platform 2D drawing object model library. It can support web, Node, desktop applications and wechat applet graphics drawing and achieve various animation effects.

This code doesn’t look neat, if nice, but why?

First of all, this is a graphics library, and this code is basically responsible for calculating the logic of our layer’s Transform matrix before rendering, that is, every frame before rendering.

In this case, no other way of writing it would perform as well as this straightforward expansion. When written this way, there is no need to use any loop or other logic, just pull the contents from the index directly to compare, which is the highest performance.

But in general code, if you’re not so performance-sensitive, you don’t have to write it like this, you can write it in a different way to make it shorter.

Why this case?

All of our code styles should be context-specific, and if you see a framework or library that’s a little bit more rigid and less elegant, you should look at that framework or library, and there’s probably a good reason for that.

What’s the most important thing to focus on when writing code?

We should consider the following points

  • Style (the same set of code should be consistent)
  • Efficiency (When writing code, you should consider the efficiency of the code, and try to write efficient code)
  • convention
  • Use scenarios (also combined with scenarios, but never at the expense of code readability for maximum efficiency)
  • design

Left-pad incident of the year

Leftpad is a simple string-handling function

  • When the string is not as long as we want it to be, we add several characters to the left of it to complete it
module.exports = leftpad; 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

Slot point of the event itself

  • NPM module granularity

  • Code style.

  • Code quality/efficiency

Optimize the code above

  • Cleaner code
  • efficiency

About repeatπŸ‘‰ repeat Polyfill/MDN

Some key words

  • Time complexity
  • Fast power

A piece of blind science: [Left-pad incident] is the NPM circle happened in that year “a dozen lines of code module caused by the bloody crime”. The left-pad tool module was removed from NPM by Azer, and all NPM packages that relied on it directly or indirectly, including Babel, React, etc., died sadly.

Why did the author delete the bag? What happened was that Azer wrote a tool called Kik and posted it on NPM. One day, a company lawyer with the same name came to him and asked him to remove it. When Azer refused, the lawyer went to NPM, and NPM transferred the management rights to the package to the company — of course, Azer was furious. Free all self-published packages from NPM. Is the sauce πŸ˜–

Traffic light status switch

To achieve a switch multiple traffic light state switch function

Version of a

Unencapsulated, unscalable, unattractive (FAIL)

How to optimize?

First of all, the data should be encapsulated. Before data encapsulation, the data should be abstracted first, and some information should be hidden after abstraction

We want to achieve traffic lights, essentially

  • We’re going to receive a set of states
  • Then perform certain instructions (such as changing the element class) based on this set of states
  • And then do a state switch

Version 2

The data is encapsulated, as are the state-switching operations

keywords

  • Data abstraction

Version 3

The above is data abstraction. In the last article, we mentioned the concept of process abstraction, which can also be implemented through process abstraction.

parsing

  • Switching state itself is a polling operation, so we can abstract the previous polling method from a polling method.
  • A list of function operations is passed in the polling method
  • Then pull out the current function in turn
  • Then execute the function

keywords

  • Procedural abstraction
  • Higher-order functions

Version 4

You can also use async… To achieve await, first of all, traffic light disassembly is mainly two operations

  • Waiting for the
  • State switch

keywords

  • Imperative writing

Although the above writing method has been optimized, but there are still places to improve

Check if it’s a power of four

4 to the 0 is 1

4 to the first power is equal to 4

4 to the second power is 16

.

4 to the fourth power is 64

.

Version of a

The compasses

keywords

  • power
  • factoring
  • Time complexity

Version 2

Version 3

Power of four, then it’s converted to binary

  • The home page must be 1
  • It’s going to be 0’s
  • And we have an even number of zeros

keywords

  • Constant complexity
  • Bitwise and

Version 4

function isPower0fFour(num){ num = parseInt(num).toString(2); // Convert binary string return /^1(? :00)*$/.test(num); // Match with regular expression}Copy the code

Shuffle the deck

correctness

Is it correct if I write it as follows?

We can test that if this shuffle is fair, then if we shuffle 10 million times and add the corresponding digits in each position of the array, the sum should be about the same

But as you can see from the results, it’s smaller

To improve the

To improve the

  const cards = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];

  function * draw(cards){
    const c = [...cards];

    for(let i = c.length; i > 0; i--) {
      const pIdx = Math.floor(Math.random() * i);
      [c[pIdx], c[i - 1]] = [c[i - 1], c[pIdx]];
      yield c[i - 1];
    }
  }

  const result = draw(cards);
  console.log([...result]);
Copy the code

Some of the concepts of algorithms come up in the following cases, but algorithms are not our current topic, so we’ll talk more about them later!

conclusion

I attended the byte youth training camp, so I prepared a re-learning front-end series. Due to the time, I may only be able to learn notes.

Update time: one essay will be published each day in the order of the course

Instructor: Byte front-end/Nuggets development lead – Moon Shadow

If any of the above is wrong, please point out in the comments section!


Xiao Ke love to finish click a “like” before leaving! πŸ˜—