A qualified mid-level front-end engineers must master the skills of 28 JavaScript

Foreword

Text codes corresponding to the specific use and detailed comments are on my github, connected to the bottom of the source code

1. The data type of the object is determined

Object.prototype.toString used with closures to return a different estimation function is determined by passing the different types, one line of code, simple and elegant and flexible (initials an incoming note type parameter)

This function is not recommended for detecting the type of packaging may be generated on basic data types, since the call will first boxing operation parameter

2. ES5 method to achieve an array map

It is worth mentioning that the second parameter map as the first argument to the callback of this point, if the first argument is a function of the arrow, then the second set because of this lexical binding function of the arrow fail

The other is to deal with sparse arrays, to judge by hasOwnProperty current target element exists under the array (thanks to friends comment area)

3. Using an array of map reduce implementation method

4. ES5 filter array implementation method

5. Method reduce implementation array of filter

6. ES5 implement some methods of the array

Array perform some method if it is an empty array, will always eventually return false, while an array of every method in another array if it is an empty array, it will always returntrue

7. ES5 reduce array-implemented

Because there may be a relationship between the sparse array, so reduce the need to ensure skip sparse elements, traversing the correct element and subscript (thank God code provided @ ternary)

8. A method of using an array of flat reduce implementation

Because selfFlat is dependent on this point, it is necessary to specify selfFlat traversal of this point in time reduce, otherwise it will default window thus pointing error

Principle reduce iterate through the encounter is still an element of the array is an array, conducted by ES6 its expansion operator dimensionality reduction (ES5 can use the concat method), and the array elements can also be nested inside an array, you need to recursive call selfFlat

The method flat while supporting a native depth dimension reduction parameter indicates the depth, i.e., a default is to drop one dimension array

Incoming Inifity will be passed in an array into a one-dimensional array

Each time the principle of a recursive depth parameter minus 1, if the depth parameter is 0, the direct return to the original array

9. achieve ES6 the class syntax

Internal parasitic class ES6 is based on the combined inheritance, it is the best inheritance, create an empty object by Object.create method, and this empty object inherits Object.create method parameters, let subclasses (subType) the prototype object is equal to the empty object, you can implement a prototype instance of a subclass is equal to the empty object, and the object of the empty prototype and equal parent class prototype object (superType.prototype) inheritance

The Object.create support the second argument, that is, to an empty object definition properties and property descriptor / accessor descriptor generation, we can inherit the default behavior more in line with the empty object to define a constructor property, and it is not gold internal attributes cited (enumerable: false)

The class allows the ES6 subclass inherits the parent class's static methods and static properties, and the ordinary combined parasitic inheritance can do inheritance between instances and examples, additional methods for the definition of inheritance between class and class needs, here the use Object.setPrototypeOf superType subType prototype set, thereby enabling static and static properties inherited from the parent class

10. The function currying

Instructions:

Currying is an important functional programming technique, a number of parameters of a function into a series of techniques using a parameter of the function

Functional programming compose another important function, the function can be combined, and the combined function takes a single argument, so if there are a plurality of receiving the demand and need to use a function of a function compose a combination, it is necessary to use currying function prepares the combination of partial evaluation, it always takes a single parameter

Borrowing Hu Yu blog an example of

11. currying function (with placeholders)

Instructions:

By occupying more flexible character to make curried realize the idea is that every one argument passed to go to fill placeholders last round, if the current round parameter contains a placeholder, then saved into the internal array the end of the current round of elements not to fill the current round placeholder parameter will only passed before filling placeholders

12. partial function

Instructions:

Partial function and the like curried concept, they think the difference is that a fixed partial function of several parameters you pass, then received a single the rest of the parameters, and the function will stop currying returns based on the parameters you pass function, until the number is the number of parameters to meet the parameters of the function before currying

Function.prototype.bind function is a typical representative of a partial function that accepts a second argument began, as previously added to the list of parameters parameter binding function of, and bind different is that above this function also supports accounting placeholders

13. Fibonacci number and its optimization

Using the memory function, the result of the previous operation had preserved for frequently rely on results of previous calculations can save a lot of time, e.g. Fibonacci number, the drawback is that the closure will take up additional memory object obj

14. A method of implementing a function bind

The core function of the bind method is the use of call, taking into account a number of other cases, such as

  • When the bind function call is returned as a new constructor is bound value to expire and new specified object
  • Defined Bind length and name attributes function (not enumerated attribute)
  • After binding function prototypes need to point to the original function

15. A method of implementing a function call

Principle is to function as a parameter passed in context (context) of properties to perform here in order to prevent conflicts using the Symbol Properties of type ES6

Simple module 16. CO

Instructions:

run function takes a generator function, whenever the generator function packages run function encounters yield keyword will stop, when the yield back the promise is resolved successfully will automatically call the next method proceeds to the next yield keyword, the final will form whenever a promise will be resolved successfully resolved the next promise, print the results of all analytical when all successfully resolved, Evolution is now async / await the most used syntax

17. The image stabilization function

leading to whether to perform immediately upon entering the time, trailing to whether additional trigger again after the end of a trigger event, the principle is the use of a timer, the timer is triggered if the event will once again within the specified time last cleared, that will not be executed and a new function to reset the timer until the timer exceeds a predetermined time function automatically trigger

While exposing the cancel function by a closure outwardly so that the outside directly to remove internal counter

18. throttling function

And similar anti-shake function, except that the additional use of the internal time stamp as a judge, there is no trigger event for a period of time to allow the next trigger event

19. lazy loading images

getBoundClientRect implementation, monitoring scroll event (recommendation to monitor events add throttle), the picture has been loaded will be removed from the list of DOM img tag consisting of, you need to listen for unbundling the last event after all the pictures loaded

intersectionObserver implementation, instantiate a IntersectionObserver, and it was observed that all labels img

Some state when all the elements img tag enters the visible area performs instantiation callback, the callback while passing a parameter entries, as viewed holds instances, such as boundary information of each element, the corresponding DOM node of the current element , the ratio of the current element into the viewable area, whenever a visual element into the area, the real picture is currently assigned to the img tag, while lifting its observations

20. new keywords

21. achieve Object.assign

Object.assign principle I can refer to another article blog

22. instanceof

The principle is recursively traverse right parameters of the prototype chain, and left each parameter for comparison, it returns false when traversing the prototype chain to the end, found return true

23. The realization of private variables

Use Proxy agent containing all _variables that begin with, it can not be accessed outside

Save private variable form of closure, the disadvantage that access to all instances of the same class is a private variable

Another implementation package closed, solve the shortcomings of the above kind of closure, each instance has its own private variables, the disadvantage is abandoned the simplicity of grammar class, all the privileges of a method (method to access private variables) They are stored in the constructor

By WeakMap and closures, save the current instance and all private variables at each instance of an object composed, can not access the external closure of WeakMap, use WeakMap advantage is that when there is no variable refers to an instance, it will automatically release the saved private instance variables, reduce the problem of memory overflow

24. shuffling algorithm

Earlier chrome elements for an array of less than 10 will use insertion sort, which can lead to disorder of the array is not really out of order, even if the latest version of chrome algorithm makes use of the place into a stable sort algorithm for scrambled problem is not solved

Can achieve real-order by shuffling algorithm, shuffling algorithm is divided into an array of additional in situ and ex situ, Figure One place shuffling algorithm, so no need to declare more economical memory usage, the principle is, traversing elements of the array, all of the current element and after a randomly selected, exchange

25. Singleton

Singleton pattern is achieved by performing the method Proxy interception constructor for ES6

26. promisify

Instructions:

promisify function is a callback function becomes promise helper functions for error-first style (nodejs) callback function, the principle is to error-first style callback regardless of success or failure, will perform a final callback function after the implementation, we need to do is to let the callback function of state control promise to

Proxy agent also used herein throughout fs module, to intercept get method, so that no manual methods to fs all modules are wrapped layer promisify function, more flexible

27. The process elegant async / await

Instructions:

No need each use async / await all wrapped in a layer of try / catch, more elegant, offers another idea here, if you use webpack can write a loader, AST syntax tree analysis, experience await grammar, automatically inject try / catch, such auxiliary functions are not even need to use

28. publish and subscribe EventEmitter

By on ways to register an event, trigger event trigger method to achieve loose decoupling between the event and added an extra once off and helper functions used to register only once to trigger events and logoff events

29. achieve JSON.stringify (additional)

When using JSON.stringify object into a JSON string, some illegal data type is distorted, mainly as follows

  • If the object contains toJSON method calls toJSON
  • In the array
    1. It becomes null when there is Undefined / Symbol / Function Data Types
    1. There is Infinity / NaN will become null
  • In the subject
    1. Attribute value Undefined / Symbol / Function when the data type, attribute, and values ​​are not to a string
    1. Attribute value Infinity / NaN, the attribute value becomes null
  • Value date data type of calls toISOString
  • Non-array / object / function / date complex data types becomes an empty object
  • Circular references will throw an error

In addition JSON.stringify can also pass the second and third optional parameter, interested friends can understand

Achieve longer the code, here I am ready to paste the source code corresponding to address JSON.stringify

Source

Source code , welcomed the star, after follow-up skills will be the first time to add new content

Reference material

JavaScript function topic of currying

JavaScript function combination of topics

JavaScript topics of memory function

Achieve ES6 series of private variables

Scrambled topic of JavaScript

Guess you like

Origin blog.csdn.net/weixin_33681778/article/details/91403862