JavaScript Functional Programming Example Analysis _javascript skills

Source: Internet
Author: User
Tags array length pow square root

The examples in this article describe JavaScript-functional programming. Share to everyone for your reference. The specific analysis is as follows:

JS, like other dynamic languages, can write higher-order functions, and so-called higher-order functions are functions that can manipulate functions. Because in JS the function is a thorough object, belonging to the first class of citizens, which provides a prerequisite for functional programming.

Here is an example code, from a JS tutorial, the function is to compute the average and standard deviation of the elements of the array, first of all, a list of non-functional programming:

var data = [1,1,3,5,5];
var total = 0;
for (var i = 0;i < data.length;i++) Total
  + = Data[i];
var mean = Tatal/data.length; Average is 3
//Calculation standard difference Total
= 0;
for (var i = 0;i < data.length;i++) {
  var deviation = data[i]-mean;
  Tatal + + deviation * deviation;
  }
var StdDev = math,.sqrt (total/(data.length-1));/Standard deviation is 2

To use functional programming, we have predefined help functions (helper functions):

Converts a class array object to a true array
function Array (a,n) {return
 Array.prototype.slice.call a,n| | 0);
}
Passes the function argument to the left-hand function
Partial_left (f) {
 var args = arguments;
 return function () {
  var a = array (args,1);
  A = A.concat (array (arguments));
  Return f.apply (this,a);}
 ;}
Passes the arguments of the function to the right side
function Partial_right (f) {
 var args = arguments;
 return function () {
  var a = array (arguments);
  A = A.concat (Array (args,1));
  Return f.apply (this,a);}
 ;}
The function argument is used as a template,
//The undefined value in the argument list is populated with the actual argument value.
function Partial (f) {
 var args = arguments;
 return function () {
  var a = array (args,1);
  var i = 0,j = 0;
  for (; i<a.length;i++)
   if (a[i] = = undefined)
    a[i] = arguments[j++];
  A = A.concat (Array (arguments,j));
  Return f.apply (this,a);}
 ;}
Returns a function similar to f (g ())
function compose (f,g) {return
 function () {Returns F.call (this
  , arguments));}

Here we give the complete use of functional programming JS code:

var data = [1,1,3,5,5];
var sum = function (x,y) {return x+y;};
var product = function (x,y) {return x*y;};
var neg = partial (product,-1);
var square = partial (math.pow,undefined,2);
var sqrt = partial (math.pow,undefined,0.5);
var reciprocal = partial (math.pow,undefined,-1);
All right, come on, orgasm.:)
var mean = product (reduce (data,sum), reciprocal (data.length));
var StdDev = sqrt (Product (Data,compose (square,partial (Sum,neg))), sum), mean (SUM (reciprocal ,-1)));

In addition to the reduce and map functions, the other functions are given in front of them. The reduce function resembles the inject function in Ruby:

ary = (1..10). To_a
ary.inject (0) {|sum,i|sum + i}//Result 55

JS is written as follows:

var ary = [1,2,3,4,5,6,7,8,9,10]
ary.reduce (function (sum,i) {return
 sum + i;
},0);

0 is the initial value of sum, if omitted, sum is the value of the first element of the array, which can be omitted here.

The map function is also simple, similar to the operation of each element of the array, and then returns an operation of the array, in Ruby code, for example, JS code similar to this:

A = (1..3). To_a; #数组 [1,2,3]
a.map {|x| x*2} #返回新数组 [2,4,6]

Let's analyze the long string of code below:

Sum and product define the functions for adding and multiplying elements;

Neg is also a function equivalent to: Product ( -1,X), that is, the X value is negative;

The square function is equivalent to: Math.pow (x,2), which computes the square value of x, noting that the second parameter of partial here is undefined, which means that the form participant here is filled by the first argument; it's clear: square (x) function equals Math.pow. (x,2).

The SQRT function is similar to square, and functions equivalent to: Math.pow (x,0.5), which is equivalent to calculating X's two-second square.
The last function reciprocal is also not difficult, equivalent to: Math.pow (x,-1), that is, calculate the negative side of X, which is equivalent to calculate the reciprocal of X.

Here's how to knead the various functions above the bird:

Look at the average of the calculation, very simple: first of all, calculate the elements of the array and then multiply the countdown to the length of the array, that is, the array and/array length.

Finally look at the seemingly difficult standard deviation, we'd better look inward:
First look at the layer that contains the neg:

Equivalent to function sum ( -1 * mean + x)
partial (Sum,neg (mean)

Here's a look at the Compose function:

The following is an equivalent substitution on the source code, which can again be equivalent to:
//square (SUM ( -1*mean + x)), expand again (I peel, I peel, I peel onions ...):
//math.pow (SUM ( -1*mean + x), 2);
Compose (square,sum ( -1*mean + x))

Next look at the map function:

It's clear!? That is, each element in data is an X, passed it into the following function, and then returns a computed new array, that is, the value of each element in the new array is the average of each element in data plus the minus of data, and then calculates the result of 2 of times.

Map (Data,math.pow (sum ( -1*mean + x), 2))

And then look at the reduce function outside of the map:

Adds each element value of the previous new array.
Reduce (Map (...), sum)

Then take a look at the reciprocal function:

Reciprocal reciprocal equivalent to (data.length-1) (
sum (data.length,-1))

And look at the outer product function:

Equal to and divided by (data.length-1)
product (Reduce (...), reciprocal (...)) for the new array element.

The outermost sqrt represents the square root of the result of the above division; You can compare the code of the previous non function programming, the same drop:) Seemingly afraid of a large piece of code, the analysis after the difficulty immediately to 0. If you reader the final expression or did not understand, it is completely the cat's language ability problem, welcome to ask questions.

Explain finished, finish the work, finished.

I hope this article will help you with your JavaScript programming.

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.