Using functional programming technique to write graceful javascript_ibm_javascript skills

Source: Internet
Author: User
Tags function definition sorts javascript array
Because functional programming takes a completely different approach to organizing programs, programmers who are accustomed to using an imperative paradigm may find functional programming a bit tricky. In this article, you'll learn some examples of how to use a functional style to write good, graceful code in JavaScript. I will discuss:

Functional programming concepts, including anonymous functions, different methods of calling functions, and how functions are passed as arguments to other functions.

The use of functional concepts includes: Extended array ordering, graceful code for dynamic HTML generation, and application of series functions.
The concept of functional programming

Please tell everyone. Please submit this to:


Digg

Slashdot



Many developers know how to encode in a language that describes how to specify problem-solving methods. For example, to write a function that calculates factorial, I can write a loop to describe the program, or use recursion to find the product of all numbers. In both cases, the calculation process is described in detail in the program. Listing 1 shows a possible use of C code to compute the factorial.


Listing 1. Factorial of the process style

int factorial (int n)
{
if (n <= 0)
return 1;
Else
return n * factorial (n-1);
}



Such languages are also called procedural programming languages because they define the process of solving problems. Functional programming is significantly different from this principle. In functional programming, you need to describe what the problem is. Functional programming languages are also called declarative languages. The same program that calculates the factorial can be written as the product of all numbers to N. A typical functional program that calculates factorial looks like the example in Listing 2.


Listing 2. Factorial of functional style

Factorial n, where n <= 0: = 1
Factorial N: = foldr * 1 take n [1 ...]



The second statement indicates the list of the first n digits to start with 1 (take n [1 ...] And then find their product, 1 is the primitive. This definition differs from the previous example, with no loops or recursion. It is like an arithmetic definition of a factorial function. Once you understand the meaning of library functions (take and FOLDR) and tags (list notation []), writing code is easy and readable.

You can write routines using only three lines of Miranda code, depending on the parameters, using breadth first or depth to iterate through each node of the N-fork tree, and the element can be any common type.

Historically, functional programming languages have been less popular for a variety of reasons. But recently, some functional programming languages are entering the computer industry. One example is the Haskell on the. NET platform. In other cases, some of the existing languages borrowed some concepts from functional programming languages. Examples of this borrowing are the iterators and continuation in some C + + implementations, as well as some functional constructs (functional construct) provided in JavaScript. However, by borrowing functional constructs, the overall language programming paradigm has not changed. JavaScript does not become a functional programming language because of the addition of functional constructs.

I'm now going to talk about the beauty of functional constructs in JavaScript, and how to use them in everyday coding and work. We'll start with some basic features and then use them to look at some of the more interesting apps.

anonymous functions

In JavaScript, you can write anonymous functions or functions that have no names. Why do you need such a function? Please continue reading, but first we will learn how to write such a function. If you have the following JavaScript functions:
Listing 3. A typical function

function sum (x,y,z) {
return (X+Y+Z);
}




The corresponding anonymous function should then look like the following:
Listing 4. anonymous functions

function (x,y,z) {
return (X+Y+Z);
}




To use it, you need to write the following code:


Listing 5. Apply anonymous functions

var sum = function (x,y,z) {
return (X+Y+Z);
} (1,2,3);
alert (sum);



Using functions as values

You can also use a function as a value. You can also have some variables that are assigned a function. In the last example, you can also perform the following actions:
Listing 6. assigning values using functions

var sum = function (x,y,z) {
return (X+Y+Z);
}
Alert (sum (1,2,3));




In the example in Listing 6 above, the value assigned to the variable sum is the function definition itself. In this way, sum becomes a function that can be invoked anywhere.

Different ways to call a function

JavaScript allows you to call functions in two ways, as shown in listings 7 and 8.


Listing 7. Typical application of a function

Alert ("Hello, world!");



Or


Listing 8. Using a function as an expression

(alert) ("Hello, world!");



So you can also write the following code:


Listing 9. You can use it immediately after you define a function

(function (x,y,z) {return (X+Y+Z)}) (1, 2, 3);



You can write a function expression in parentheses, and then pass it to the parameter to perform an operation on the parameter. Although in the example in Listing 8, there is a function name that is directly enclosed in parentheses, but when you use it in the way shown in Listing 9, that's not the case.

To pass a function as an argument to another function

You can also pass a function as an argument to another function. Although this is not a new concept, this concept is used extensively in subsequent examples. You can pass the function arguments, as shown in Listing 10.


Listing 10. Pass the function as a parameter and apply the function

var passfunandapply = function (fn,x,y,z) {return fn (x,y,z);};

var sum = function (x,y,z) {
return x+y+z;
};

Alert (passfunandapply (sum,3,4,5)); 12



The execution of the last alert statement outputs a value of size 12.

Using Functional concepts

The previous section describes some programming concepts that use functional style. The example given does not contain all the concepts, they are not sequential in importance, but some concepts related to this discussion. The following is a quick summary of functional styles in JavaScript:

A function does not always need a name.
Functions can be assigned to variables like other values.
function expressions can be written and placed in parentheses for later application.
Functions can be passed as arguments to other functions.

This section describes some examples of effective use of these concepts to write graceful JavaScript code. (using JavaScript functional style, you can do a lot of things beyond the scope of this discussion.) )

Extended array Sorting
First, you write a sort method that sorts the data based on the date of the array element. Writing this method in JavaScript is very simple. The sort method of a data object accepts an optional parameter, which is the comparison function. Here, you need to use the comparison function in Listing 11.

Listing 11. comparison function

function (x,y) {
return x.date–y.date;
}




To get the function you want, use the example in Listing 12.


Listing 12. Extension of the Sort function

Arr.sort (function (x,y) {return x.date–y.date;});



Where arr is a type array object. The sort function sorts all objects based on the date of the objects in the ARR array. The comparison function, along with its definition, is passed to the sort function to complete the sort operation. Use this function:

Each JavaScript object has a date attribute.
The sort function of a JavaScript array type accepts optional arguments, and optional parameters are the comparison functions used to sort. This is similar to the Qsort function in the C library.

Graceful code for dynamically generating HTML
In this example, you'll see how to write graceful code that dynamically generates HTML from an array. You can generate a table based on the values obtained from the data. Alternatively, you can use the contents of the array to generate sorted and unordered lists. You can also generate a vertical or horizontal menu item.
The code style in Listing 13 is typically used to generate dynamic HTML from an array.


Listing 13. Generate generic code for dynamic HTML

var str= ';
for (Var i=0;i<arr.length;i++) {
var element=arr[i];
str+= ... HTML Generation Code ...
}
document.write (str);



You can replace this code with the code in Listing 14.


Listing 14. Common way to generate dynamic HTML

Array.prototype.fold=function (TEMPLATEFN) {
var len=this.length;
var str= ';
for (var i=0; i<len; i++)
Str+=templatefn (This[i]);
return str;
}

function Templateinstance (Element) {
Return ... HTML Generation Code ...
}

document.write (Arr.fold (templateinstance));



I use the prototype property of the Array type to define a new function fold. You can now use the function in any of the arrays that you define later.

Application of series function
Consider the following scenario: you want to use a set of functions as a callback function. For this to happen, the Window.settimeout function is used, which has two parameters. The first parameter is the function that is called after the number of milliseconds represented by the second parameter. Listing 15 shows one way to do this.
Listing 15. Calling a set of functions in a callback

Window.settimeout (function () {alert (' first! '); Alert (' second! ');}, 5000);



Listing 16 shows a better way to do this.


Listing 16. A better way to call a series function

Function.prototype.sequence=function (g) {
var f=this;
return function () {
f (); G ();
}
};
function Alertfrst () {alert (' first! ');}
function Alertsec () {alert (' second! ');}
SetTimeout (Alertfrst.sequence (alertsec), 5000);



When handling an event, you can also use the code extension in Listing 16 if you want to call a callback after a callback is called. This may be an exercise that requires you to do it yourself, and now your interest is lit up.






Back to the top of the page




Conclusion

Functional programming in JavaScript can be applied in many areas to accomplish day-to-day activities in a graceful way. The examples in this article describe only a few things. If you find the right scenario for functional programming and apply these concepts, you will have more understanding and can increase your grace.
More from

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.