A case study of JavaScript functional programming

Source: Internet
Author: User
Tags pow

JS, like other dynamic languages, can write higher-order functions, so-called higher-order functions are functions that can manipulate functions. Because the function in JS is a thoroughly bottom object, belonging to the first class of citizens, this provides a prerequisite for functional programming.
Here is an example code, from a JS tutorial, which calculates the average and standard deviation of an array element, and first lists a notation for non-functional programming:

vardata = [1,1,3,5,5];varTotal =0; for(vari =0; i < data.length;i++) Total + = Data[i];varmean = Tatal/data.length;//average is 3//Calculate standard deviationTotal =0; for(vari =0; i < data.length;i++) {vardeviation = data[i]-mean;    Tatal + = deviation * deviation; }varStdDev =Math,. sqrt (total/(data.length-1));//Standard deviation is 2

In order to use functional programming, we pre-defined some helper functions (helper functions):

//Convert a class array object to a true array function array(a,n){  return Array. Prototype.slice.call (a,n| |0);}//Pass function arguments to the left function partial_left(f){  varargs =arguments;return  function(){    varA = Array (args,1); A = A.concat (Array (arguments));returnF.apply ( This, a); };}//Pass the arguments of the function to the right function partial_right(f){  varargs =arguments;return  function(){    varA = Array (arguments); A = A.concat (Array (args,1));returnF.apply ( This, a); };}//The function argument is used as a template, and the undefined value in the argument list is populated with the actual argument value.  function partial(f){  varargs =arguments;return  function(){    varA = Array (args,1);vari =0, j =0; for(; i<a.length;i++)if(A[i] = = =undefined) A[i] =arguments[j + +]; A = A.concat (Array (arguments, j));returnF.apply ( This, a); };}//Returns a function similar to f (g ()) function compose(f,g){  return  function(){    returnF.call ( This, G.apply ( This,arguments)); };}

Here we give a completely functional programming of the JS code:

vardata = [1,1,3,5,5];varsum = function(x, y){returnX+y;};varProduct = function(x, y){returnX*y;};varNeg = partial (product,-1);varSquare = Partial (Math. POW,undefined,2);varsqrt = partial (Math. POW,undefined,0.5);varReciprocal = partial (Math. POW,undefined,-1);//Well, the climax comes to the bird:)varmean = Product (reduce (data,sum), reciprocal (data.length));varStdDev = sqrt (product (Reduce (map (square,partial (Sum,neg)), sum), mean (SUM (reciprocal1))));

In addition to the reduce and map functions, the other functions are given earlier. The reduce function is similar to the inject function in Ruby:

ary = (1..10).to_aary.inject(0) {|sum,i|sum + i} //结果为55

JS is spelled 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, and if omitted, the sum is the value of the first element of the array, which can be omitted.

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

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

Let's analyze that long string of code:)
Sum and product define the functions of adding and multiplying elements;
Neg is also a function function equivalent to: Product ( -1,X), that is negative for the X value;
The square function is equivalent to: Math.pow (x,2), which calculates the square value of x, noting that the second parameter of the partial is undefined, which means that the form here is filled by the first argument (see the code for the previous partial); and, again, the point: Square (x) function equals Math.pow (x,2).
The SQRT function is similar to square in that the function is equivalent to: Math.pow (x,0.5), which is equivalent to calculating x two times.
The last function, reciprocal, is no more difficult, equivalent to: Math.pow (x,-1), that is, calculates the negative of X, which is equivalent to counting the reciprocal of X.
Here is how to knead the various functions above the bird:)
The calculation of the average is simple: first, the array elements are computed and then multiplied by the inverse of the array length, that is, the array and/or array lengths.
Finally look at the seemingly difficult standard deviation, we'd better see from the Inside Out:
First look at the layer containing the neg:

//等价于函数sum(-1 * mean + x)partial(sum,neg(mean)

Here's a look at the Compose function:

//下面在源代码上做了等价替换,可以再次等价于://square(sum(-1*mean + x)),再次展开(我剥,我剥,我剥洋葱...)://Math.pow(sum(-1*mean + x),2);compose(square,sum(-1*mean + x))

Next look at the map function:

//很清楚吧!?即data中每一个元素都为一个x,将其传入后面的函数,然后返回一个计算后的新数组,即新数组中的每个元素的值是data中的每个元素加上data负的平均数,然后对其结果计算2次方的结果。map(data,Math.pow(sum(-1*mean + x),2))

Then look at the reduce function outside map:

//将前面新数组的每个元素值加起来。reduce(map(...),sum)

Then take a look at the reciprocal function:

//等价于求(data.length-1)的倒数reciprocal(sum(data.length,-1))

Then look at the outer product function:

//等价于新数组元素的和除以(data.length-1)product(reduce(...),reciprocal(...))

The outermost sqrt represents the square root of the result of the above division; You can control the previous non-functional programming code, is the same drop:) Seemingly a lot of scary code, after the analysis of the difficulty will be immediately 0. If you crossing finally said that still do not understand, it is completely the language of the cat problem, welcome to ask questions.
After the explanation, after the completion of the resumption of work.

A case study of JavaScript functional programming

Related Article

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.