Brief introduction
Lodash is a library of JavaScript tools with consistent interface, modularity, and high performance features. Provides a large number of tool functions, and for this reason, makes Lodash a library that is the most dependent on other libraries in the NPM package library.
Just as jquery adds global $ before all functions, Lodash uses global _ to provide quick access to tools.
varrequire(‘lodash‘);
Improve developer Productivity
//copy一个JS对象//原生方法var a = {a:1,b:2,c:3};var b = {};for(varin a) { b[key] = a[key];}//lodash方法var b = _.clone(a);
A single method, one line of code can be used to achieve the replication of the JS object.
But here, Lodash's high-efficiency features don't show
varA = {};//Create an object with a large number of elements, otherwise the copy time is too small, statistics are inaccurate for(varI=0;i<1000000; i++) {a[i.tostring ()] =Math. Floor (Math. Random () *100000);}varb = {};//console.time (label);//console.timeend (label);//One by one corresponds, used to count the code run time between the twoConsole.time (' native copy '); for(varKeyinchA) {B[key] = A[key];} Console.timeend (' native copy ');varc = {};console.time (' Lodash clone '); c = _.clone (a); Console.timeend (' Lodash clone ');
Operation Result:
copy473581ms
Improve program operation efficiency
However, in most cases, the tool functions provided by Lodash can significantly improve the efficiency of the program.
var Array= [];//Generate an array of 100w lengths and assign random numbers for(varI=0;i<1000000; i++) {Array. Push (Math.floor (Math.random () *10000))}//Native foreach traversalConsole.time (' native for each ');Array.ForEach( function (key) {}); Console.timeend (' native for each ');//lodash ForEach TraversalConsole.time (' Lodash for each ');_.ForEach(Array, function (key) {}); Console.timeend (' Lodash for each ');
Operation Result:
forEach32forEach11ms
You can see that the operating speed is reduced by nearly three times times. I do not know whether the computer environment, the software version of the reasons, the results of the operation on someone else's computer appeared
forEach98forEach4ms
The speed difference is nearly 25 times times.
Lazy calculation
The reason why Lodash can significantly improve computational efficiency is its application to lazy computing.
Lazy evaluation, a concept in computer programming, is designed to minimize the work that a computer is doing.
Also known as lazy computing, especially for functional programming languages. An expression is not evaluated immediately after it is bound to a variable, but is evaluated when the value is taken, that is, the statement, such as X:=expression; (Assigning the result of an expression to a variable) an explicit call to this expression is computed and the result is placed in X, but the evaluation of the subsequent expression itself can be deferred, regardless of what is actually in X, until a reference to its value is passed through the subsequent expression to the X. This fast-growing dependency tree is ultimately calculated to generate a symbol that is visible to the outside world.
Here is a simple lazy calculation example, a simple redundancy function.
function mod (a,b){ if(b==1return0; elsereturn a % b ;}mod((1+3)*2,1) // 0
We can see that because B is 1, we don't use the value of a, but we still calculate the expression (1+3), and the calculation here is wasteful. Lazy evaluation can avoid this situation.
Look at the following code:
var arr = _.range(100);var a = _.chain(arr) .map(function (x) { console.log(1); return x+1; }) .take(10) .value();
The result will output 100 1.
Why is that? Is it not that the lazy evaluation is used in the Lodash? should not output 10 1?
It turns out that only 200 of the array in Lodash will start the lazy evaluation.
var arr = _.range(200);var a = _.chain(arr) .map(function (x) { console.log(1); return x+1; }) .take(10) .value();
In this way, the output will be 10 1.
Lodash Common tool functions
//1. Basic for Loop. for (var i = 0 ; i < 5 ; i++) {//.... } //2. Using Array ' s join and Split methods array . Apply ( null , array (5 )). foreach (function () { //... }); //Lodash _.times (5 , function () { //... });
- Iterate algebraic groups and return deep nested properties in each item
//Fetch The name of the first pet from each ownervarOwnerarr = [{"owner":"Colin","Pets": [{"Name":"Dog1"}, {"Name":"Dog2"}]}, {"owner":"John","Pets": [{"Name":"Dog3"}, {"Name":"Dog4"}]}];//Array ' s map method.Ownerarr.map ( function(owner){ returnowner.pets[0].name;});//Lodash_.map (Ownerarr,' Pets[0].name ');
- Gets a random value within the specified range
// Get a random number between 15 and 20.// Naive utility methodfunction getRandomNumber(minmax){ return Math.floor(Math.random() * (maxminmin;}getRandomNumber(1520);// Lodash_.random(1520);
The random method in Lodash is more powerful and flexible than the native method above. You can pass in only one parameter as the maximum value, or you can specify the returned result as a floating-point number.
_.random(20); // Return random number between 0 to 20_.random(1520true); // Return random floating numbers between 15 and 20
- Select a list item randomly from the list
var luckyDraw = ["Colin""John""James""Lily""Mary"];function pickRandomPerson(luckyDraw){ varMath.floor(Math.random() * (luckyDraw.length -1)); return// John// Lodash// Colin
You can also specify the number of returned elements
var luckyDraw = ["Colin""John""James""Lily""Mary"];//LodashGetting2 random item_2// [‘John‘,‘Lily‘]
- Select part of a property from an object to make a new object
//Naive method:returning A new object with selected propertiesObject. Prototype.pick = function(arr) { var_this = This;varobj = {}; Arr.foreach ( function(key){Obj[key] = _this[key]; });returnobj;};varObja = {"Name":"Colin","Car":"Suzuki","Age": -};varOBJB = Obja.pick ([' car ',' age ']);//{"Car": "Suzuki", "Age": +}//LodashvarOBJB = _.pick (Obja, [' car ',' age ']);//{"Car": "Suzuki", "Age": +}
- Remove some properties of an object
//Naive method:remove An array of keys from ObjectObject. Prototype.remove = function(arr) { varthat = This; Arr.foreach ( function(key){ Delete(That[key]); });};varObja = {"Name":"Colin","Car":"Suzuki","Age": -};obja.remove ([' car ',' age ']); obja;//{"name": "Colin"}//LodashObja = _.omit (Obja, [' car ',' age ']);//{"name": "Colin"}
LODASH,NPM the most dependent libraries in the package warehouse