Introduction to js function Programming

Source: Internet
Author: User

Introduction to js function Programming

Js function Programming

The concept of function is to constantly use existing functions to combine new functions.

Functional programming has five distinctive features:

1. The function is the first citizen.
The function is equal to other data types.

2. Only expressions are used and no statements are required.
An expression is a simple operation and always has a return value;
A statement (statement) is an operation that has no return value.

3. No side effects
It refers to internal and external interactions of the function (the most typical case is to modify the value of the global variable ),
Generates results other than the operation.

4. Do not modify the status
Variables are often used to save the state ). If the variable is not modified, the status cannot be saved in the variable,
Function programming uses parameter save status

5. Transparent reference
It means that the function runs independently of external variables or States and only depends on input parameters. If the parameters are the same at any time,
The return values obtained by referencing the function are always the same.

The significance of functional programming:
1. Simple code and fast development
2. Close to natural language, easy to understand
3. More convenient code management
4. Easy concurrent programming
5. Hot code upgrade

--------------------- Split line ------------------------

In JavaScript, a function itself is a special object and belongs to the top-level object,
Does not depend on any other object. Therefore, you can use a function as an outgoing/incoming parameter,
It can be stored in variables and can do anything other objects can do.

Self-called functions (recursion-Self-called functions) are actually a form of high-order functions.

Function programming example:

 

// The general implementation of factorial function factorial (n) {if (n = 1) {return 1;} else {return factorial (n-1) * n ;}} // implement function mul (a, B) {return a * B;} function dec (x) {return x-1;} function equal (a, B, b) {return a = B;} function factorial (n) {if (equal (n, 1) {return 1;} else {return mul (n, factorial (dec (n )));}}
--------------------- Split line ------------------------
Function kerialization:
Converts a function that accepts multiple parameters into a function that accepts a single parameter (the first parameter of the original function,
And return the technology of the new function that accepts the remaining parameters and returns results.

In my understanding, we need to call a method a () repeatedly. One of its parameters is difficult to change the value under certain conditions,
It is too troublesome to write many times for each call, and it does not reflect the class of problems it describes and solves. In this case,
To avoid these two problems, we fixed the variable that is not easy to change and generated a function to deal with them.
This type of problem.
Simple implementation of addition Keri:

 

 

// Add function adder (num) {return function (x) {return num + x ;}} var add5 = adder (5); var add6 = adder (6); console. log (add5 (1); // 6console. log (add6 (1); // 7
Here, the add5 function solves the addition problem with the base number of 5. You only need to pass a parameter,
You do not have to add two parameters for each call, as in a common addition function.
// Calculate the n var powerOfN of m = function (n) {return function (m) {var res = 1; for (var I = 0; I <n; ++ I) {res * = m;} return res ;};// generate var powerOf2 = powerOfN (2); var powerOf3 = powerOfN (3) on demand ); // call the parameter passing console. log (powerOf2 (3); console. log (powerOf3 (2 ));
Keri general implementation:

 

 

function curry(fn) {    var args = [].slice.call(arguments, 1);    return function() {        var inargs = [].slice.call(arguments);        console.log(args.concat(inargs));        return fn.apply(null, args.concat(inargs));    }}function curry(fn) {    var args = [].slice.call(arguments, 1);    return function() {        var inargs = [].slice.call(arguments);        console.log(args.concat(inargs));        return fn.apply(null, args.concat(inargs));    }}function add(num1, num2) {    return num1 + num2;}var newAdd = curry(add, 5);console.log(newAdd(6));
Kerihua will reduce the universality of function usage and increase the specificity of use. Using kerihua requires careful identification.
It is applicable to scenarios where the requirements are met. Otherwise, the Code may become too long to reduce the readability of the Code.
--------------------- Split line ------------------------
High-order functions
A high-order function is a further abstraction of a function. It is a function that uses other functions as input or returns a function as output.
The most common applications of higher-order functions include map, reduce, forEach, and filter,
They all operate array elements in different ways by passing in different functions.
Simple application:

 

 

Function foo (f, g) {return function () {return f. call (null, g. apply (null, arguments); // return f (g. apply (null, arguments); yes} var sum = function (x, y) {return x + y;} var square = function (x) {return x * x;} var squareofsum = foo (square, sum); squareofsum (2, 3); // 25
Next let's take a look at how to transition from procedural programming to functional programming:

 

1> Form 1

 

var sum = function(x, y) {  return x + y;}var square = function(x) {  return x * x;}function foo(){  return square( sum(2, 3) );}foo();// 25
2> Form 2

 

 

var sum = function(x, y) {  return x + y;}var square = function(x) {  return x * x;}function foo(f, g){  return f( g(2, 3) );}foo(square, sum);// 25
3> Form 3

 

 

var sum = function(x, y) {  return x + y;}var square = function(x) {  return x * x;}function foo(f, g){  return function(){    var num1 = arguments[0];    var num2 = arguments[1];    console.log(num1, num2);// 2 3    var temp = g(num1, num2);    console.log(temp);// 5    return f(temp);  };}var myfunc = foo(square, sum);myfunc(2, 3);// 25
4> Form 4

 

 

var sum = function(x, y) {  return x + y;}var square = function(x) {  return x * x;}function foo(f, g){  return function(){    var temp = g.apply(null, arguments);    return f(temp);  };}var myfunc = foo(square, sum);myfunc(2, 3);// 25
The last form is what we want.

 

--------------------- Split line ------------------------
Other examples:

1>

 

function foo(fn, array, value){  var res = array.map(function(ele){    return fn.apply(null, [ele].concat(value));  });  return res;}function add(x, y) {  return x + y;}function sub(x, y) {  return x - y;}console.log( foo(add, [1, 2, 3], 3) );// [4, 5, 6]console.log( foo(sub, [1, 2, 3], 3) );// [-2, -1, 0]

2>

 

 

function multicast(fn) {  return function (){    var pre = arguments[0];    var rest = arguments[1];    var ret = pre.map(function(ele) {      return fn.apply(this, [ele].concat(rest));    });    return ret;  }}function add(x, y) {  return x + y;}var newAdd = multicast(add);console.log(newAdd([1,2,3],3));// [4, 5, 6]function sub(x, y) {  return x - y;}var newSub = multicast(sub);console.log(newSub([1,2,3],3));// [-2, -1, 0]

 

 

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.