(translation, continuous updating) Tips on JavaScript (Part Two)

Source: Internet
Author: User
Tags array sort gcd greatest common divisor shuffle

Considering the article is too long, not easy to read, here to separate the second, if there is a follow-up, every 15 points of knowledge is divided into one ...

#29-Use cached memory to let recursive functions run faster
The wave non-tangent sequence (Fibonacci sequence) Presumably everyone is not strange (for genius, before this beast completely did not know what the ghost, although often use recursion), we can write the following function in 20 seconds:

var function (n) {    return N < 2 N:fibonacci (n-1) + Fibonacci (N-2);}

It does work, but it's not very efficient. It does a lot of repetitive computing work, and we can speed it up by caching the results of previous calculations.

var fibonacci = (function() {    var cache = {        0:0,        1: 1    };     return function (n) {        return n <= 1 Cache[n]: (cache[n] = cache[n-1] + cache[n-2]);}    ) ()

At the same time, we can define a higher order function that will receive a function as a parameter and the parameter function will return a cached version that has been remembered.

var function (func) {    var cache = {};     return function () {        var key = Array.prototype.slice.call (arguments). toString ();         return  in cache? Cache[key]: (Cache[key] = func.apply (this, arguments));     = Memoize (Fibonacci);

We can use memoize in many cases ()
GCD (Greatest common divisor)

var gcd = memoize (function(A, b    ) {var  t;     if (A < b) T=b, b=a, a=t;      while (b! = 0) t=b, b = a%b, a=t    ; return A;}) GCD (//= 3

Factorial calculation

var factorial = memoize (function(n) {    return (n <= 1)? 1:n * Factorial (n-1
   
    //
    = +
   

#28-Cauchy (topical) and topical applications
Curry (locally applied)
Currying the following function

F:x*y_-r

Convert to a function in the following form:

F ':x_> (Y->r)

We only call F ' with the first argument, instead of the two arguments to invoke F. The returned result is a function that we have called with the second argument and return the result value.
So, if we call the non-Curry function f:

F (3,5)

Then call the Curry function f ':

F (3) (5)

Case:
The non-curry add ()

function Add (x, y) {  return x + y;} Add (3, 5);   // _> 8

The curry Add ()

function ADDC (x) {  returnfunction  (y) {    return x + y;  }} ADDC (3) (5);   // _> 8

The algorithm of the curry:
Curry takes a two-tuple function and returns a unary function that contains a unary function.
Currying

(xxy→r) → (x→ (y→r))

JavaScript code:

function Curry (f) {  returnfunction(x) {    returnfunction( Y) {      return  f (x, y);   }}

Local applications:
The following function is used by the local application

F:x*y_-r

Given a fixed value, a parameter is passed in to produce a new function:

F ': Y->r

F ' and F are different, but he only needs to fill in the second parameter, which is why F ' is one less than the number of F's parameters.
Case:
The first parameter of the binding function is PLUS5 with the plus 5 through the function:

function plus5 (y) {  return 5 + y;} PLUS5 (3);  // _> 8

Algorithms for local applications:
A local call takes a two-tuple function and a value, and produces a unary function.
Local: ((xxy→r) xx) → (y→r)
JavaScript code:

function partapply (f, x) {  returnfunction(y) {    return  F (x, y);}  }

# # 2016-01-30 Update # # #

#27-short-circuit Evaluation (not understand what is a thing, so for the moment do not translate it)
Short-circuit evaluation points out that the second argument is executed only if the argument of the first argument is not sufficient to determine the value of the expression: when the first argument's and (&&) function returns FALSE, the overall value will also be false ; When the first parameter is the OR (| |) Is true, the overall value is also true.
Here is the test condition and the IsTrue function and the IsFalse function:

var test = True; var isTrue = function() {  console.log (' test is true. ') );}; var isFalse = function() {  Console.log (' Test is false. ') );};

Use the and (&&) logic:
Normal statement.

Normal statement. If(test) {  isTrue ();    _> true}//above function using ' && ' completion (Test && isTrue ());  _> true 

Use the OR (| |) Logic:

Test = False; if (!  Test) {  isFalse ();    _> false. } (Test | | isFalse ());  _> false.  

Logical OR (| |) Statements can also be used to set default values for the parameters of a function:

function Thesameoldfoo (name) {     name = name | | ' Bar ' ;    Console.log ("My best friend's name is" + name);} Thesameoldfoo ();  My best friend's name is Barthesameoldfoo (' Bhaskar ');  My best friend's name is Bhaskar  

The logical AND (&&) statement can also be used to avoid exceptions to attributes that use undefined, case:

var dog = {   bark:function() {     console.log (' Woof Woof ');   }};/ /Call Dog.bark ();d Og.bark (); Woof woof.//But if bog is undefined, dog.bark () throws an error "cannot read property ' bark ' of undefined." We can use && to avoid this situation. Dog&&dog.bark ();   In this case, the Dog.bark () will only be called when bog exists.  

# # 2016-01-28 Update # # #

#26-filtering and sorting of string lists
You might have a large list of strings that you need to filter and sort by alphabetical order.
In our example, we will use JavaScript to hold a series of keywords in different languages, but as you can see, they are duplicated and not sorted alphabetically. So this is a perfect string list (array) to test this javascript trick.

var keywords = [' do ', ' if ', '-', ' for ', ' new ', ' Try ', ' var ', ' case ', ' Else ', ' enum ', ' null ', ' this ', ' true ', ' void ', ' wit ' H ', ' Break ', ' catch ', ' class ', ' Const ', ' false ', ' super ', ' throw ', ' while ', ' delete ', ' export ', ' import ', ' return ', ' SWITC H ', ' typeof ', ' Default ', ' extends ', ' finally ', ' Continue ', ' debugger ', ' function ', ' do ', ' if ', '-', ' for ', ' int ', ' new ', ' Try ', ' var ', ' byte ', ' case ', ' char ', ' Else ', ' enum ', ' Goto ', ' long ', ' null ', ' this ', ' true ', ' void ', ' with ', ' Break ', ' CA ' Tch ', ' class ', ' Const ', ' false ', ' final ', ' float ', ' short ', ' super ', ' throw ', ' while ', ' delete ', ' double ', ' export ', ' Impo RT ', ' native ', ' public ', ' return ', ' static ', ' switch ', ' throws ', ' typeof ', ' Boolean ', ' Default ', ' extends ', ' finally ', ' PA ' Ckage ', ' private ', ' abstract ', ' Continue ', ' debugger ', ' function ', ' volatile ', ' interface ', ' protected ', ' transient ', ' Implements ', ' instanceof ', ' synchronized ', ' do ', ' if ', ' on ', ' for ', ' Let ', ' new ', ' Try ', ' var ', ' case ', ' Else ', ' enum ', ' E Val ', ' null ', ' this ', ' true '', ' void ', ' with ', ' break ', ' catch ', ' class ', ' Const ', ' false ', ' super ', ' throw ', ' while ', ' yield ', ' delete ', ' export ', ' I Mport ', ' public ', ' return ', ' static ', ' switch ', ' typeof ', ' Default ', ' extends ', ' finally ', ' package ', ' private ', ' Continu E ', ' debugger ', ' function ', ' arguments ', ' interface ', ' protected ', ' Implements ', ' instanceof ', ' do ', ' if ', '-', ' for ', ' l ' Et ', ' new ', ' Try ', ' var ', ' case ', ' Else ', ' enum ', ' eval ', ' null ', ' this ', ' true ', ' void ', ' with ', ' await ', ' break ', ' catch ' ', ' class ', ' Const ', ' false ', ' super ', ' throw ', ' while ', ' yield ', ' delete ', ' export ', ' import ', ' public ', ' return ', ' Stati C ', ' Switch ', ' typeof ', ' Default ', ' extends ', ' finally ', ' package ', ' private ', ' Continue ', ' debugger ', ' function ', ' Argum Ents ', ' interface ', ' protected ', ' Implements ', ' instanceof '];

Since we are not going to change the original list, we will use a higher-order function called filter, which will be filtered based on the function we passed to it and return a new filtered array. The judgment statement compares the index of the current keyword with the index in the new list, and pushes the item into a new array if the index matches.
Finally, we use the sort function to sort the filtered list with a comparison function as a unique parameter, returning a list sorted alphabetically.

var filteredandsortedkeywords = keywords  . filter (function (keyword, index) {      return Keywords.indexof ( keyword) = = = index;    })  . Sort (function (A, b) {      if (a < b) return-1;      else if (a > B) return 1; return 0;});      

ES6 (ES 2015) using the ARROW function will look simpler:

Const Filteredandsortedkeywords = Keywords  . Filter ((keyword, index) = keywords.indexof (keyword) = = = index)  . Sort ((A, b) + = {      if (a < b) return-1;      else if (a > B) return 1;      return 0;});     

This is a list of keywords that are filtered and sorted:

Console.log (filteredandsortedkeywords);//[' abstract ', ' arguments ', ' await ', ' Boolean ', ' Break ', ' byte ', ' case ', ' Catch ', ' char ', ' class ', ' const ', ' Continue ', ' debugger ', ' Default ', ' delete ', ' Do ', ' double ', ' Else ', ' enum ', ' eval ', ' ex ' Port ', ' extends ', ' false ', ' final ', ' finally ', ' float ', ' for ', ' function ', ' goto ', ' if ', ' Implements ', ' import ', ' in ', ' in ' Stanceof ', ' int ', ' interface ', ' let ', ' long ', ' native ', ' new ', ' null ', ' package ', ' private ', ' protected ', ' public ', ' retur  n ', ' short ', ' Static ', ' super ', ' switch ', ' synchronized ', ' this ', ' throw ', ' throws ', ' transient ', ' true ', ' Try ', ' typeof ', ' var ', ' void ', ' volatile ', ' while ', ' with ', ' yield ']

# # 2016-01-27 Update # # #

#25-Using an immediate execution function expression

Called "Iffy" (iife-immediately executes a function expression) is an anonymous function that is useful in JavaScript and can be called immediately.

(function() {//do something}) () 

Enclosing the anonymous function in parentheses converts the function anonymous function into a function expression or variable expression. Therefore, we use an unnamed function expression instead of a simple anonymous function under the global scope (or anywhere else).

Similarly, we can create a name for him and execute the function immediately:

(somenamedfunction = function(msg) {    console.log (msg | | "Nothing for Today!" )}) (); Output, nothing for today!! Somenamedfunction ("Javascript rocks!!"); Output, Javascript Rocks!! Somenamedfunction (); Output  , nothing for today!!

For more information, click on the link below Link1 link2
Demo: JsPerf

# # 2016-01-26 Update # # #

#24-use = = = instead of = =
= = (or! =) compares the two to the same type when comparing. = = = (or!==) will not, he will compare the two to do type comparison and value comparison, relative to = =, the comparison will be more rigorous.

[Ten] = =/     /true[10] = = =/    /false "ten" = =/     /true "ten" = = =//    false[] = = 0        //true[] = = = 0
   //false "" = = False    //true but true = = "A" is false "" = = = False   //False

#23-A more method of converting values
It is very common to convert a string to a number. The simplest and fastest (jspref) way to implement is to use the + (plus) algorithm.

var one = ' 1 '; var numberone = +one;//number 1

You can also use the-(minus) algorithm's conversion type and turn it into a negative value.

var one = ' 1 '; var negativenumberone =-one;//Number-1

#22-Empty An array
You define an array and want to empty its contents. Typically, you would do this:

var list = [1, 2, 3, 4];function empty () {    //empty array    list = [];} Empty ();  

But there is a more high-performance approach.
You can use this code:

var list = [1, 2, 3, 4];function empty () {    //empty array    list.length = 0;} Empty ();  

· List = [] Assigns a variable reference to that array, and no other references are affected. This means that references to the contents of the previous array remain in memory, causing a memory leak.
· list.length = 0 Delete everything inside the array, this does not need to reference anything else
However, if you have a copy of the array (A and copy-a), if you use List.length = 0 To delete its contents, the copy will also lose its contents.

var foo = [];var bar = [];var]foo2 = Foo;var bar2 = Bar;foo = [];bar.length = 0; console. Log (foo, bar, Foo2, bar2);//[] [] [1, 2, 3] []     

More details on the StackOverflow: Difference-between-array-length-0-and-array

#21-"Shuffle" the array sort (random sort)
This code here uses the Fisher Yates Shuffle algorithm to shuffle a specified array (randomly sorted).

function Shuffle (arr) {    var i,        J,        temp;    for (i = arr.length-1; i > 0; i--) {        j = Math.floor (Math.random () * (i + 1));        temp = Arr[i];        Arr[i] = arr[j]; arr[j] = temp;} return arr;};       

Case:

var a = [1, 2, 3, 4, 5, 6, 7, 8];var B = Shuffle (a); Console.log (b);//[2, 7, 8, 6, 5, 3, 1, 4] 

The random tips provided in the commentary by the Netizen @ Magic Day Mans:

Arr.sort (function() {return math.random ()-0.5;});

Measurement available, thanks for sharing!

#20-Functions that return an object can be used for chained operations
When creating the function of an object-oriented JavaScript object, the function returns an object that will allow the function to be chained and written together to execute.

function person (name) {  this.name = name;  This.sayname = function() {    Console.log ("Hello My name is:", this. Name);    return this;  };  This.changename = function(name) {this.name = name; return this;};} var person = new Person ("John");p erson.sayname (). ChangeName ("Timmy"). Sayname ();//hello My name is:john// Hello My name is:timmy         

#19-String Secure connection
Suppose you have some variables of unknown type and you want to connect them together. To be sure, algorithmic operations are not applied at cascade time:

var one = 1; var = 2; var three = ' 3 '; var result = '. Concat (one, both, three);//"123"  

Such a connection is not exactly what you expect. Conversely, some concatenation and addition can lead to unexpected results:

var one = 1; var = 2; var =' 3 '; var result = one + three + three;//"" "  and not" 123"
    

When it comes to performance, comparison of joins and Concat, they perform almost the same speed. You can learn more about concat in MDN.

#18-Faster rounding
Today's tip is about performance. Have you seen the double wavy line "~ ~" operator? It is also sometimes referred to as a double not operator. You can use it faster as a math.floor () substitute. Why is it?
The unit moves to the 32-bit conversion input-(input + 1), so the double displacement converts the input to-(-(input + 1)), which is a great tool that tends to be 0. For the number entered, it will mimic Math.ceil () to take negative values and Math.floor () to take positive values. If the execution fails, it returns 0, which may be useful in the case of a nan when used in place of Math.floor () failure.

Unit shift Console.log (~1337)    // -1338//Dual Displacement Console.log (~~47.11)  //-47console.log (~~-12.88)//-- 12console.log (~~1.9999)///-1console.log (~~3)///-      3//failure Console.log (~~[])//-0 Console.log (~~nan)  ///-0console.log (~~null)//-0//greater than 32-bit integer fails Console.log (~ ~ (2147483647 + 1) = = = (2147483647 + 1))//-0

Although ~ ~ may have a better performance, for readability, please use Math.floor ().

#17-node.js: Let the module run when it's not require
In node, you can tell your program to do two different things depending on whether you run require ('./something.js ') or node something.js. This is useful if you want to interact with one of your independent modules.

if (!  module.parent) {    //Run ' node Something.js '    app.listen (8088, function() {        console.log (' app listening on Port 8088 ');}    )} else {    //use ' Require ' ('/.something.js ') '    module.exports = app;}    

For more information, see the documentation for modules

#16-passing parameters to the callback function
By default, you cannot pass parameters to the callback function, as follows:

function Callback () {  console.log (' Hi human ');} document.getElementById (' Someelem '). AddEventListener (' click ', callback); 

You can take the advantages of JavaScript closures to pass parameters to the callback function, as shown in the following example:

Function Callback (A, b) {  return function() {    console.log (' sum = ', (A +B));}  } var x = 1, y = 2;d ocument.getelementbyid (' Someelem '). AddEventListener (' Click ', Callback (x, y));   

What is a closure? Closures refer to a function that is independent of (free) variables. In other words, the function defined in the closure remembers the environment it was created in. Learn more see MDN so this way when called, the parameter X/y exists in the scope of the callback function.
Another method is to use a binding method. For example:

var alerttext = function(text) {  alert (text);}; document.getElementById (' Someelem '). AddEventListener (' Click ', Alerttext.bind (this, ' Hello '));

There are some slight differences in performance between the two methods, see Jsperf for details.

# # 2016-01-25 Update # # #

Previous address: (translation, continuous updating) JavaScript tips (i)

(translation, continuous updating) Tips on JavaScript (Part Two)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.