Examples of javascript functional programming and javascript programming

Source: Internet
Author: User

Examples of javascript functional programming and javascript programming

This example describes javascript functional programming. Share it with you for your reference. The specific analysis is as follows:

Javascript can write higher-order functions like other dynamic languages. The so-called higher-order functions can operate functions. In JavaScript, functions are a thorough object and belong to the first type of citizens. This provides a prerequisite for functional programming.

The following is an example code from a js tutorial. The function is to calculate the average value and standard deviation of array elements. First, it lists a method of non-functional programming:

Var data = [1, 1, 3, 5]; var total = 0; for (var I = 0; I <data. length; I ++) total + = data [I]; var mean = tatal/data. length; // mean is 3 // calculate the standard deviation 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); // The standard deviation is 2

To use function-based programming, We pre-define some help functions (helper functions ):

// Convert the class array object to the true Array function array (a, n) {return Array. prototype. slice. call (a, n | 0) ;}// pass the function arguments to the left-side function partial_left (f) {var args = arguments; return function () {var a = array (args, 1); a =. concat (array (arguments); return f. apply (this, a) ;};}// pass the real parameter of the function to function partial_right (f) {var args = arguments; return function () {var a = array (arguments); a =. concat (array (args, 1); return f. apply (this, ); };} // This function real parameter is used as a template. // The undefined value in the real parameter list is filled with the actual real parameter value. Function partial (f) {var args = arguments; return function () {var a = array (args, 1); var I = 0, j = 0; (; I <. length; I ++) if (a [I] === undefined) a [I] = arguments [j ++]; a =. concat (array (arguments, j); return f. apply (this, a) ;};}// returns a function similar to f (g () function compose (f, g) {return function () {return f. call (this, g. apply (this, arguments ));};}

The following is the JavaScript code fully programmed using functions:

Var data = [, 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); // Well, climbing: var mean = product (reduce (data, sum), reciprocal (data. length); var stddev = sqrt (product (reduce (map (data, compose (square, partial (sum, neg (mean), sum ), reciprocal (sum (data. length,-1 ))));

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

Ary = (1 .. 10). to_policy.inject (0) {| sum, I | sum + I} // The result is 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 it is omitted, sum is the value of the first element of the array, which can be omitted here.

The map function is also very simple. It is similar to performing operations on every element of the array and then returning an array after the operation. Taking the ruby code as an example, the js Code is similar to this:

A = (1 .. 3). to_a; # array [1, 2, 3] a. map {| x * 2} # Return the new array [2, 4, 6]

Next we will analyze the long string of code :)

Sum and product define the function of adding and multiplying elements;

Neg is also a function equivalent to: product (-1, x), that is, evaluate the negative value of x;

The square function is equivalent to Math. pow (x, 2) is used to calculate the square value of x. Note that the second parameter of partial is undefined, which means that the parameter is filled by the first real parameter; here we can understand that the square (x) function is equal to Math. pow (x, 2 ).

The sqrt function is similar to square, and its function is equivalent to Math. pow (x, 0.5), which is equivalent to the open quadratic side of x.
The last function, reciprocal, has no difficulty. It is equivalent to Math. pow (x,-1), that is, calculating the negative cubic of x, which is equivalent to calculating the reciprocal of x.

The following is how to knead the above functions together :)

First, let's look at the calculation of the average value. It is very simple: Calculate the sum of the array elements and then multiply the reciprocal of the array length, that is, the length of the array and/array.

Finally, it seems difficult to calculate the standard deviation. We 'd better look at it from the inside out:
First look at the layer that contains the neg:

// Equivalent to the sum (-1 * mean + x) partial (sum, neg (mean) Function)

The following describes the compose function:

// The following is an equivalent replacement in the source code, which can be equivalent to: // square (sum (-1 * mean + x) and expand again (I peel, I peel, I peeled onions ...): // Math. pow (sum (-1 * mean + x), 2); compose (square, sum (-1 * mean + x ))

Next, let's look at the map function:

// Is it clear !? That is, each element in data is an x, which is passed into the following function, and then a new calculated array is returned, that is, the value of each element in the new array is the mean of adding a negative data to each element in data, and then the result is calculated to the power of 2.

map(data,Math.pow(sum(-1*mean + x),2))

Next, let's look at the reduce function outside map:

// Add each element value of the new array. Reduce (map (...), sum)

Then let's take a look at the reciprocal function:

// It is equivalent to the reciprocal (sum (data. length,-1) of (data. length-1 ))

Let's look at the outer product function:

// Equivalent to the sum of elements in the new array divided by (data. length-1) product (reduce (...), reciprocal (...))

The sqrt at the outermost layer calculates the square root of the result obtained by the above division. You can compare the code of the previous non-function programming with the same result. :) a huge amount of code that looks quite scary, after analysis, the difficulty is immediately reduced. If you still haven't understood what the audience finally said, it is a question about the language expression ability of the cat. You are welcome to ask questions.

The explanation is complete, and the success is done.

I hope this article will help you design javascript programs.

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.