preface
As for technology, only by repeated learning can we move forward steadily.
1. Function currying
Function currying is a way of recursively degrading a function with multiple parameters. The core of its implementation is:
1. Thinking about how to cache each parameter passed in
2. Compare the passed parameters with the incoming parameters of the target function
Here we cache parameters in the form of closures, as follows:
The usage is as follows:
Is it just a use of the summation above?
👆 For this question, it’s necessary to go to 🤔. In fact, using the idea of function currying, we can better achieve the encapsulation of functions.
For example, if you listen for an event and there is an operation to remove that event, you can use the idea of currying to encapsulate code.
Or if an input A has A unique and corresponding output B, then it is safer and more independent to think about such projects from A larger perspective. It’s also easy to maintain.
2. About arrays
Handwritten Map method
The map() method maps a new array based on the callback function
Handwritten filter method
The filter() method returns an array with each item true as the result of the callback.
The difference between “filter” and “map” is that “filter” maps the item whose condition is true, and “map” maps each item.
Handwriting reduce method
The reduce() method iterates, and the result of the callback function is taken as the first parameter of the next parameter.
Write every method
The every() method tests whether all the elements in an array pass the test of a specified function. It returns a Boolean value.
Handwriting some method
The some() method tests whether at least one element in the array passes the provided function test. It returns a value of type Boolean.
Handwritten find method
The find() method returns the value of the first element in the array that satisfies the provided test function. Otherwise, return undefined.
Flattening array
Flattening nested arrays occurs more frequently in business data processing scenarios. So how does that work?
- Use the ES6 syntax flat(num) method to level an array.
If you want to flatten a multilevel nested array, you need to pass an integer indicating the level to be flattened. This returns a new array with no effect on the original array.
- Flatten the array using the reduce() method.
Using Reduce to iterate, the core idea is recursive implementation.
- The analog stack implements array flattening
This method is a simulation stack and is relatively optimal in performance.
3. Image lazy loading & lazy function
The core idea behind lazy image loading is to use a local placeholder, or null, for the SRC attribute of img. Then define a data-set attribute to save the real image path, and assign the value of data-img attribute to SRC when certain conditions are reached.
The following is a lazy image loading by scroll event listener. When all the images are loaded, remove the event listener and remove the HTML tag.
Scroll events may cause performance problems. It can automatically observe whether the IMG tag enters the viewable area through IntersectionObserver.
Instantiate an instance of IntersectionObserver, accepting two arguments: callback is the callback function for changes in visibility, and option is the configuration object (this parameter is optional).
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 unviewing it.
The above is a lazy image loading implementation.
What’s the difference between lazy loading and lazy functions?
Lazy loading is a kind of lazy function, but lazy function is not only lazy loading, it can also include another direction.
Another way to do this is to rewrite the function so that every time you call the function, you don’t need to make a conditional judgment. Instead, you need to make a conditional judgment once when you initialize the function. That is, you don’t need to make a conditional judgment again next time, such as compatibility on event listeners.
4. The preload
Preloading, as the name suggests, means loading ahead of time, such as images.
If you need to view the data, you can directly fetch the data from the local cache. The advantage of preloading is that if an image is too large, the request to load the image will be slow, the page will appear blank, and the user experience will become worse. In order to improve the user experience, the image should be loaded into the local cache in advance, and the user will see the image as soon as the page is opened.
5. Throttling & shaking
For functions with high frequency triggers, we often think about throttling or shaking to optimize performance.
Throttle implementation principle is through the timer and time difference to do judgment. The timer can be delayed. The event will not be executed immediately after the event starts but will be executed again after the event ends. The time difference event is executed as soon as it starts and stops as soon as the time ends.
Combine the two features to encapsulate the throttling function:
Function throttling guarantees that the actual event handler will be executed once within a specified period of time, no matter how frequently the event is fired.
If the event is triggered again within a specified time, the last timer will be cleared, that is, the function will not be executed and a new timer will be set, until the function in the timer is automatically triggered after the specified time.
6. Implement the new keyword
7. Instanceof
The instanceof operator detects whether the constructor’s prototype property is present on the prototype chain of an instance object.
8. Implement call, apply, bind
- call
The principle of the call function is to borrow the method, the key is to implicitly change the reference to this.
- apply
The principle of the apply function and call are the same, the key lies in the processing and judgment of parameters.
The call() method is similar to the apply() method, except that the call() method accepts a list of arguments, while the apply() method accepts an array of arguments.
- bind
The bind() method creates a new function. When bind() is called, this of the new function is specified as the first argument to bind(), and the remaining arguments are used as arguments to the new function.
Key ideas of implementation:
1. Copy and save the original function, new function and the original function prototype link
2. Create a new function and call the original function in the new function
9. Encapsulate data type functions
10. Self-memory function
11. Check whether circular references exist
Copy functions
Copying data has always been an integral part of business development, and I have written an article about deep and shallow copying data before.
- Copy data through Depth-first Thinking (DFS)
Depth first is to think through the vertical dimension, and the object ring is also considered in the process of processing.
The core idea of solving object ring is to save and copy first. The original object is first copied through a container, and before each copy, it is checked to see if the object already exists in the container. This disconnects the original object from the copied object.
- Copying Data through Breadth-first Thinking (BFS)
Breadth first is to think through the horizontal dimension, by creating the relationship between the source queue and the copy array queue to achieve copy.
13. Promise series
I’ve written an article about Promise before.
Promsie.all
Promsie.race
Promsie.finally
14. Implement async – await
15. Simple subscription-publish
16. Singletons
Singleton pattern: ensures that there is only one instance of a class and provides a global point of access to it. The implementation method is to first determine whether the instance exists, if there is a direct return, if not, first create and then return.
17. The achieve Object. The create
The object.create () method creates a new Object, using an existing Object to provide the __proto__ of the newly created Object.
The method is to implement the existing object and new object prototype is a shallow copy of the process.
18. Implement ES6 class syntax
Use the object.create () method to inherit the instance Object of a subclass from the prototype Object of the parent class. With object.setPrototypeof (), you can inherit static methods and static properties from the parent class.
19. Implement a compose function
The compose function is the idea of composing the combined function, and then output the value. In redux source code for middleware processing.
- Use a while loop
- It is implemented using reduce iterations
20. Implement asynchronous parallel functions
Fn is a function that returns a Promise.
Fn is not a return Promsie then pack a layer:
21. Implement asynchronous serial functions
22. Implementation of private variables
The above is the encapsulation of private variables implemented by ES5. By using WeakMap, the private property corresponding to each instance can be extended. The private property cannot be accessed externally and disappears with the destruction and destruction of this object.
One small detail worth mentioning here is the following code:
Above are different ways of writing the methods that hang onto the prototype and the methods that are unique to each instance. What’s the difference? (PS: can be manually printed)
Calling a method on the stereotype then the value of the private variable is the value of the last instance that called the stereotype method. The value of the previous instance is changed accordingly, so there is a problem…
WeakMap can solve the above problem: the method is hung to the prototype, and the results produced by invoking the same instance are consistent over different periods.
The source code
Javascript –, welcome star
conclusion
I always think that if there is an input, there must be an output, and that summary is the best way to output. Therefore, with an article like this, I hope readers can calm down to write and understand the thinking and running process of code, and I think they will have a deeper understanding of JS. (PS: We can discuss together)
As summarized above, we will continue to update if there are new content…
The resources
28 JavaScript Skills a Qualified intermediate front End engineer needs to master
MDN