Lu Xun said : Only those who have read excellent library source code , To be worthy of a real warrior .
compact
Create a new array , Contains all the non false elements in the original array . for example false, null,0, “”, undefined, and NaN They're all supposed to be “ False value ”.
Note that the above description does not include [],{} Because in js in , The two values are implicitly converted to true. In other words, the function doesn't filter these two values .
Official code :
export function compact(array){
let resIndex = 0;
const result = []
if(array == null){ // Will be able to undefined Get rid of it because undefined == null by true
return result
}
for(const value of array){
if(value){
result[resIndex++] = value
}
}
return result
}
Personal understanding of code :
export function compact(array){
let resIndex = 0;
const result = []
if(array == null){ // Will be able to undefined Get rid of it because undefined == null by true
return result
}
result = array.filter(v=>Boolean(v))
return result
}
Direct use of filter Traversal , utilize boolean, To convert elements to true or false .
concat
Create a new array , take array With any array or Values are linked together .
var array = [1];
var other = _.concat(array, 2, [3], [[4]]);
console.log(other);
// => [1, 2, 3, [4]]
console.log(array);
// => [1]
relatively speaking ,concat Function depends on a few more tool functions .
- arrayPush Array adding method
- copyArray Copy array elements
- baseFlatten Flat hierarchical array
export function concat(){
let length = arguments.length; // Get the number of parameters
if (!length) {
return [];
}
let args = Array(length - 1); // Take the length of the parameter other than the first one
let array = arguments[0]; // Take the first item of the array
let index = length;
while (index--) {
args[index - 1] = arguments[index];
}
console.log(args); // Take the first parameter, which is the target array , As -1 Item added as array
// Determine whether a parameter is an array , No, just convert it to an array , If it is an array, copy an array , Reuse arrayPush Method , Push the parameters of each item into the array .
return arrayPush(Array.isArray(array) ? copyArray(array) : [array], baseFlatten(args, 1));
}
copyArray
Copy an array , This operation does not affect the original array .
Parameters | explain |
---|---|
soure | Original array parameters |
array | Result array |
export function copyArray(source,array){
let index = -1;
let length = source.length;
array || (array = Array(length));
while(++index < length){
array[index] = source[index]
}
return array
}
baseFlatten
This method is mainly used for flat array operation
export function baseFlatten(array, depth, predicate, isStrict, result) {
let index = -1;
let length = array.length;
predicate || (predicate = isFlattenable); // isFlattenable Determine if it's an array
result || (result = []);
while (++index < length) {
let value = array[index];
console.log(value);
if (depth > 0 && predicate(value)) { // If the level is greater than 0 And the item is an array
if (depth > 1) { // If the level of recursion is greater than 1 In this case, we will continue to solve the problem recursively
baseFlatten(value, depth - 1, predicate, isStrict, result);
} else { // If recursion is required, the level of recursion is 1 The situation of , All items are added to the target array
arrayPush(result, value);
}
} else if (!isStrict) {
result[result.length] = value;
}
}
return result;
}
isFlattenable(value){
return Array.isArray(value)
}
divergent thinking , As long as the function is passed through the depth Variable , To control the level of screening , So I want to flatten all arrays , How to operate it ?
function flattern(arr) {
return arr.reduce((cur, next) => cur.concat(Array.isArray(next) ? flattern(next) : next), []);
}
arrayPush
Add elements into the original array , Will change the original array structure , similar push Method
let index = -1;
let length = values.length;
let offset = array.length;
while (++index < length) {
array[index + offset] = values[index];
}
return array;
summary
- ++index and index++ The difference ,++i That is to add before use ,i++ That is to use it first and add it later . In front of ++ The subscript will not cross the boundary , After ++ The subscript crossing the line .
- lodash library The operation array generally does not affect the original array .
read lodash Source code tour array method -compact and concat More articles about
- Read with your hands Mybatis Source code ( 3、 ... and ) Cache
Preface Hello everyone , This article is MyBatis The last article in the series , The first two articles : Read with your hands Mybatis Source code ( One ) Structure and Read with your hands Mybatis Source code ( Two ) Execution , It mainly explains MyBatis How is it? ...
- lodash Source analysis of the array difference set
The shabby and poor appearance of the outside world , It can balance my inner world . -- Calvino < smoke and clouds > This article is for reading lodash Chapter 17 of the source code , Subsequent articles will be updated to this repository , welcome star:pocket-lodas ...
- Read with your hands Mybatis Source code ( One ) Structure
Preface Today we will share our common persistence layer framework ——MyBatis Working principle and source code analysis of , The follow-up will focus on Mybatis Framework to do some more in-depth explanation , After that, the content will be placed in the official account menu bar. : In the serial …- In frame analysis , Welcome to explore ! ...
- Read with your hands Mybatis Source code ( Two ) Execution
Preface The last article mentioned MyBatis How to build configuration class , Also said that the MyBatis In the process of operation, it is mainly divided into two stages , The first is to build , The second is implementation , So this article will take you to understand MyBatis How to start from the end of the build , To carry out ...
- From the source point of view finish() Method execution flow
1. finish() Method Overview Let's look at it first finish The definition of the nonparametric version of a method : /** * Call this when your activity is done and should be c ...
- lodash Data type of source code analysis
All the sadness , There is always a trace of joy left behind , All the regrets , There will always be a perfect corner left , I am in the deep sea of iceberg , Looking for the gap of hope , But when I woke up , A glimpse of the beautiful sunshine ! -- A few meters This article is for reading lodash Source code Chapter 18 , Subsequent articles will be updated to ...
- read lodash Source code from slice Sparse array and dense array
Despicable is the pass of the despicable , Noble is the epitaph of noble . -- The north island < answer > Look at the North Island. It's from these two lines , The noble is dead , Only despicable people are left to roam the world . This article is for reading lodash The first chapter of source code , Subsequent articles will be updated to this warehouse ...
- lodash Source code analysis compact Traversal in
When I was a child , Nostalgia is a small stamp , I'm here , Mother is over there . When I grow up , Nostalgia is a narrow ticket , I'm here , The bride is over there . Later on , Nostalgia is a short grave , I'm outside , Mother is inside . And now , Homesickness is a shallow bay ...
- lodash Source code analysis Hash cache
In the warm Pavilion of little dream , I collect the misty rain of the whole season for you . -- Love < Linghe > This article is for reading lodash The fourth source code , Subsequent articles will be updated to this repository , welcome star:pocket-lodash gitbo ...
- lodash Source code analysis List cache
Yesterday I walked along the river bank / Stroll to / Where the reeds bend to drink By the way, chimney / Write me a long letter in the sky It's a bit sloppy / And my heart / So bright as the candle in front of your window / A little bit ambiguous / be certainly unavoidable / Because of the wind -- Love < Because of the wind & ...
Random recommendation
- Gephi visualization ( One )—— Use Gephi Toolkit establish Gephi application
stay Prefuse I've been up and down for a while , Found it amiable , Easy to use . But it's always on gephi, When importing data and running again , Always in the heart secretly praise gephi The most gorgeous , No match , Of course ,gephi It also has its own shortcomings , however ge ...
- Android Mobile phone guard --home Interface layout
In this paper, the implementation of when from splash Interface into the hone Interface time , Produce a gradual fade in animation effect , stay onCreate A method is invoked in initAnimation(), The code is as follows : /** * Add fade in animation */ pri ...
- [Python] solve python The chain extend The technique of
as everyone knows python Medium list Yes. extend Of , function The aim is to combine the two list Merge into one . for example [1,2,3].extend([4,5,6])=[1,2,3,4,5,6] If there is one list Of list, ...
- C# Read web source code
#region 1. Read Web source code + static string ReadHtml(string urlStr,int type) /// <summary> /// Read Web source code + ...
- SQL General query details
One . Cross connect (cross join) Cross connect (cross join): There are two kinds of , Explicit and implicit , No on Clause , It returns the product of two tables , It's also called Cartesian product . for example : The following statement 1 And statement 2 The result is the same . sentence 1: implicit ...
- Problems in audio software development debug Methods and tools
This article was originally written by the author . Such as reprint , Please indicate the source . thank you ! Audio software development is the same as other software development , All need to be debugged . Audio software debugging has the same place with other software debugging methods , There are different places , At the same time, some special tools are needed for debugging , With these methods ...
- BASIC-3 Alphabetic figure loop character string
Based on practice Alphabetic figure The time limit :1.0s Memory limit :256.0MB Problem description The use of letters can form some beautiful graphics , Here is an example : ABCDEFG BABCDEF CBABCD ...
- vim The simple use of and some commonly used commands
For the first time vi, There are a few points to be reminded of :1. use vi After opening the file , Is in 「 Command line mode (command mode)」, You want to switch to 「 Insertion mode (Insert mode)」 To be able to input text . Switching method : stay 「 Command line mode ...
- The development of enterprise firewall iptables
1.1 Principles of security optimal allocation in Enterprises Try not to configure the external network for the server ip , It can be forwarded by proxy or mapped by firewall . Concurrency is not particularly large, there are extranets ip, You can start the firewall service . Large concurrent cases , Can't open iptables, Affect performance , ...
- spring( Four ) Manual integration web project (SSH)
It's clear spring Of IOC and AOP, The last one is integration SSH Frame the , recorded , It should be used in the future . --WH One .web How to use in a project spring? When tomcat Startup time , It should be loaded spring Configuration of ...