Compile the elegant JavaScript_ibm with functional programming technology

Source: Internet
Author: User

Because functional programming uses a completely different way of organizing programs, programmers who are used to using imperative examples may find functional programming a little hard to learn. In this article, you will learn some examples about how to use the functional style and use JavaScript to write good and elegant code. I will discuss:

Function programming concepts include anonymous functions, different methods for calling functions, and methods for passing functions as parameters to other functions.

The Application of functional concepts includes extended array sorting, beautiful code generated by Dynamic HTML, and applications of series functions.
Functional Programming Concepts

Please tell everyone. Please submit this:


Digg

Slashdot



Many developers know how to encode the language that specifies a solution by describing "how to do. For example, to compile a function to calculate factorial, I can write a loop to describe the program, or use recursion to find the product of all numbers. In both cases, the computing process is described in detail in the program. Listing 1 shows a possible C code used to calculate a factorial.


List 1. Process-style factorial

Int factorial (int n)
{
If (n <= 0)
Return 1;
Else
Return n * factorial (n-1 );
}



These languages are also called procedural programming languages because they define the process of solving the problem. Functional programming is significantly different from this principle. In functional programming, You need to describe the question "What is it ". Functional programming languages are also called declarative languages. The same factorial program can be written as the product of all numbers to n. The typical function program for calculating factorial looks like the example in Listing 2.


List 2. factorial in a functional Style

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



The second statement indicates that you want to obtain the list of the first n numbers starting from 1 (take n [1 ..]), and then find out the product of them. 1 is the base element. This definition is different from the previous example. There is no loop or recursion. It is like the arithmetic definition of a factorial function. Once you understand the meaning of the library functions (take and foldr) and the mark (list notation []), it is easy to write the code and the readability is also good.

You can write routines with only three lines of Miranda code. Based on the parameters, You can traverse each node of the n-tree with breadth-first or depth-first, and the elements can be of any common type.

Historically, functional programming languages are not popular for many reasons. But recently, some functional programming languages are entering the computer industry. One example is Haskell on the. NET platform. In other cases, some existing languages borrow some concepts from functional programming languages. Some C ++ implementation iterators and continuation, as well as some functional construct provided in JavaScript, are examples of such borrow. However, the general language programming examples have not changed by using function-based construction. JavaScript has not become a functional programming language because of the addition of functional structures.

I want to talk about the beauty of functional structures in JavaScript and how to use them in daily coding and work. We will start with some basic functions and use them to view more interesting applications.

Anonymous Functions

In JavaScript, you can write anonymous functions or functions without names. Why do we need such a function? Continue reading, but first we will learn how to write such a function. If you have the following JavaScript Functions:
Listing 3. Typical Functions

Function sum (x, y, z ){
Return (x + y + z );
}




Then the corresponding anonymous function should look as follows:
Listing 4. Anonymous Functions

Function (x, y, z ){
Return (x + y + z );
}




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


Listing 5. Applying anonymous Functions

Var sum = function (x, y, z ){
Return (x + y + z );
} (1, 2, 3 );
Alert (sum );



Use functions as values

You can also use a function as a value. You can also assign values to variables of functions. In the last example, you can also perform the following operations:
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, the value assigned to the variable sum is the function definition itself. In this way, sum becomes a function that can be called anywhere.

Different Methods for calling Functions

JavaScript allows you to call a function in two ways, as shown in listing 7 and 8.


Listing 7. Typical function applications

Alert ("Hello, World! ");



Or


Listing 8. Using functions as expressions

(Alert) ("Hello, World! ");



You can also write the following code:


Listing 9. You can use the function immediately after defining it.

(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 for calculation. Although the function name in the example in listing 8 is directly included in the brackets, this is not the case when you use it as shown in listing 9.

Passing functions as parameters to other functions

You can also pass functions as parameters to other functions. Although this is not a new concept, it is widely used in subsequent examples. Function parameters can be passed, as shown in listing 10.


Listing 10. Passing the function as a parameter and applying 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



Execute the last alert statement and output a value of 12.

Use functional concepts

The previous section describes some functional programming concepts. The given examples do not contain all concepts, and they are not sequential in terms of importance. They are just some concepts related to this discussion. Below is a quick summary of the functional style in JavaScript:

The name is not always required for a function.
Functions can be allocated to variables like other values.
Function expressions can be written and placed in brackets for future use.
Functions can be passed as parameters to other functions.

This section describes some examples of using these concepts to write beautiful JavaScript code. (Using the JavaScript functional style, you can do many things beyond the scope of this discussion .)

Extended array sorting
Compile a sorting method to sort the data based on the date of the array element. Writing this method in JavaScript is very simple. The Data Object sorting method accepts an optional parameter, which is a comparison function. Here, you need to use the comparison function in listing 11.

Listing 11. comparison functions

Function (x, y ){
Return x. date-y. date;
}




To obtain the required function, use the example in listing 12.


Listing 12. Sorting Function Extension

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



Here, arr is a type array object. The sorting function sorts all objects based on the date of objects in the arr array. The comparison function and its definition are passed to the sorting function to complete the sorting operation. Use this function:

Each JavaScript Object has a date attribute.
The sorting function of the array type in JavaScript accepts optional parameters, which are the comparison functions used for sorting. This is similar to the qsort function in the C library.

Dynamically generate beautiful HTML code
In this example, we will see how to write beautiful code and dynamically generate HTML from the array. You can generate a table based on the values obtained from the data. Alternatively, you can use the array content to generate a list of sorted and unsorted items. You can also generate a vertical or horizontal menu item.
The Code style in listing 13 is usually used to generate dynamic HTML from arrays.


Listing 13. generate common dynamic HTML code

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 methods for generating 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 attribute of the Array type to define the new function fold. This function can be used in any array defined later.

Application of series Functions
Consider the following situation: you want to use a group of functions as the callback function. To achieve this purpose, the window. setTimeout function is used, which has two parameters. The first parameter is the function called after the second parameter represents the number of milliseconds. Listing 15 shows a way to complete this operation.
Listing 15. Calling a group of functions in the callback

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



Listing 16 shows a better way to complete this operation.


Listing 16. A better way to call a series of functions

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 processing an event, if you want to call another callback after calling a callback, you can also use the code extension in listing 16. This may be an exercise that you need to complete on your own. Now your interest is ignited.






Back to Top




Conclusion

Function programming in JavaScript can be applied in many fields to complete daily activities in a beautiful way. The example in this article only describes several situations. If you find a suitable scenario for functional programming and apply these concepts, you will have more understanding and will be able to improve your beauty.
More from

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.