1. Determine the data type


Use Object. The prototype. ToString cooperate closures, in judging the accuracy of the data type, at the same time to make this function is very flexible, by passing in different types of judgment to return different judging function (note that when introduced into the type parameter capitalize the first letter)

ES5 implements the array map method


It is worth noting that the map’s second argument points to this in the first argument callback. If the first argument is an arrow function, the setting of the second this is invalid because of the lexical binding of the arrow function

3. Implement the array map method using Reduce


ES5 implements the array filter method


5. Use reduce to implement the array filter method


6. ES5 implements some methods of arrays


An array executing some always returns false if it is an empty array, while an array in the every method of another array always returns true if it is an empty array

7. ES5 implements the reduce method of arrays


8. Implement the flat method of array using reduce


Because selfFlat depends on this, you need to specify this of selfFlat during reduce traversal. Otherwise, the selfFlat will point to Window by default and an error will occur

Principle Traverses the number group by reduce. When an element of the array is still an array, the extension operator of ES6 is used to reduce its dimension (CONCat method can be used in ES5). However, the array element may have nested arrays internally, so selfFlat needs to be recursively called

Meanwhile, the native Flat method supports a depth parameter to indicate the depth of dimensionality reduction. The default value is 1, which means that the array is reduced by one dimension


Passing Inifity turns the passed array into a one-dimensional array


The principle is that the depth parameter is decreased by 1 at each recursion. If the depth parameter is 0, the array is returned

9. Implement ES6 class syntax


Create method creates an empty Object and inherits this empty Object from the parameters of object. create method. Then let the prototype of subclass (subType) equal to the empty object, we can realize the prototype of subclass is equal to the empty object, and the empty object is equal to the inheritance of supertype. prototype

Object. Create supports the second argument, which defines attributes and attribute/accessor descriptors for the generated empty Object. We can give this empty Object a constructor property that more conforms to the default inheritance behavior. It is also an internal property that cannot be enumerable (Enumerable: False)

ES6 class allows subclasses to inherit static methods and static attributes from their parent class, whereas ordinary parasitic combinatorial inheritance can only be implemented from instance to instance. For class to class inheritance, additional methods need to be defined. Here we use Object.setProtoTypeof to set superType to the prototype of subType, thus being able to inherit static methods and static properties from the parent class

10. Coriolization of functions


Usage:


Currization is an important technique in functional programming, the technique of converting a function that takes multiple arguments into a series of functions that take one argument

Functional programming compose another important function, and to be able to function combination, the combination of function accepts only one parameter, so if you have to accept a number of function demand and need to use compose function combination, will need to use the part of curry to prepare composite function, let it always only accepts a parameter

To borrow an example from Hu Yu’s blog


11. Function Corrification (placeholder support)


Usage:




If the current round parameter contains a placeholder, it is placed at the end of the internal saved array. The element of the current round does not fill the placeholder of the current round parameter, but only fills the placeholder passed in before

12. Partial functions


Usage:


The concept of partial functions is similar to that of Currization. In my opinion, the difference is that partial functions fix several arguments you pass in and take the rest at once, whereas currization returns the function based on the arguments you pass in until the number of arguments is equal to the number of arguments the function had before currization

The function.prototype. bind Function is an example of a partial Function that starts with the second argument, which is pre-added to the parameter list of the binding Function. Unlike Bind, this Function also supports placeholders

13. Fibonacci sequence and its optimization


Using function memory, you can save a lot of time for computations that frequently rely on previous results, such as the Fibonacci sequence. The disadvantage is that obJ objects in the closure take up extra memory

14. Implement the bind method


At its core, the bind method makes use of call, taking into account other cases such as

  • When the function returned by bind is called as a constructor by new, the binding value is invalidated and changed to the object specified by new
  • Define the length and name attributes of the bound function (non-enumerable attributes)
  • The prototype of the bound function must point to the original function

Implement the call method


The principle is to execute the function as an attribute of the context parameter passed in. ES6 Symbol type is used to prevent attribute collisions

16. Simple CO module


Usage:


The run function takes a generator function, stops every time the generator function wrapped by the run function encounters the yield keyword, and automatically calls the next method to execute to the next yield keyword when a promise after the yield is resolved successfully. In the end, every time a promise is resolved successfully, the next promise will be resolved. When all the results are resolved successfully, all the results of the parsing will be printed, which evolves into the async/await syntax that is most used today

17. Function anti-shake


The principle is that the timer is used. If the event is triggered again within the specified time, the last timer will be cleared, that is, the function will not be executed and a new timer will be set. The timer function is automatically triggered until the specified time is exceeded

It also exposes a cancel function through the closure, allowing the outside to clear the internal counter directly

18. Function throttling


Similar to function anti-shake, the difference is that the internal additional use of timestamp as a judgment, in a period of time has not triggered the event to allow the next event to trigger

19. Lazy loading of images


The implementation of getBoundClientRect listens for scroll events (it is recommended to add throttling for listening events). After loading images, they will be deleted from the DOM list composed of img tags. Finally, all images need to be unbound after loading listener events


IntersectionObserver is implemented by instantiating a intersectionObserver and making it observe all IMG tags

When img tags into the viewing area to perform the callback when instantiated, at the same time to pass in a callback entries parameters, save the instance to observe all the elements of some state, such as the boundary of each element, the current element corresponding DOM node, the ratio of the current element into the viewing area, whenever an element into the viewing area, Assigns the real image to the current IMG tag while unobserving it

20. The new keyword


21. The achieve Object. Assign


The Object. Assign principle can be referenced in another blog of mine

22. instanceof


The principle is to recursively traverse the prototype chain of the right argument, and return false when it reaches the end of the prototype chain and true when it finds the left argument

23. Implementation of private variables


Use Proxy to Proxy all variables that start with _ and make them inaccessible to external access


The disadvantage of holding private variables in closures is that all instances of a class access the same private variable


Another implementation of the closure, which addresses the disadvantage of the above closure, is that each instance has its own private variables. The disadvantage is that the brevity of class syntax is abandoned and all privileged methods (methods that access private variables) are stored in constructors


With WeakMap and closure, objects composed of the current instance and all private variables are saved during each instantiation. WeakMap in the closure cannot be accessed externally. The advantage of using WeakMap is that there is no need to worry about memory overflow

24. Shuffle algorithm

Earlier Chrome used insertion sort for arrays with less than 10 elements, which resulted in an out-of-order that wasn’t really out of order. Even though the latest version of Chrome uses the in-place algorithm to make sorting stable, the out-of-order problem hasn’t been solved




Real out-of-order can be achieved through shuffling algorithm, which is divided into in-situ and non-in-situ. Figure 1 shows the in-situ shuffling algorithm, which does not need to declare additional arrays to save memory usage. The principle is to iterate through the elements of the number group in turn, and randomly select one of the current element and all subsequent elements to swap

25. Singleton mode


The singleton pattern is implemented through the execution method of the ES6 Proxy interceptor constructor

26. promisify


Usage:


Promisify is a helper function that turns a callback into a promise, which is suitable for the error-first style (NodeJS) callback. The principle is that the last callback is executed after the completion of an error-first style callback, whether it succeeds or fails. All we need to do is let the callback control the state of the Promise

Proxy is used to Proxy the whole FS module and intercept the GET method, so that there is no need to manually wrap all the methods of FS module with a layer of promisify function, which is more flexible

27. Handle async/await gracefully


Usage:


There is no need to wrap a try/catch layer every time you use async/await, which is more elegant. Here is another idea. If you use Webpack, you can write a loader, analyze AST syntax tree, encounter await syntax, and automatically inject try/catch. You don’t even need to use auxiliary functions

The source code

Source code, welcome star, in the future there will be follow-up tips to add new content as soon as possible

The resources

JavaScript thematic functions Currize JavaScript thematic functions composition JavaScript thematic functions memory ES6 series of private variables to implement JavaScript thematic disorder