Writing graceful JavaScript with functional programming techniques

Source: Internet
Author: User
Tags sorts javascript array

Writing graceful JAVASCRIPT_IBM with functional programming technique
Font: [Increase decrease] type: Reprint
Functional programming languages have been around for quite some time in the academic world, but historically they have not had the tools and libraries to use. With the advent of Haskell on the. NET platform, functional programming has become more prevalent. Some traditional programming languages, such as C + + and JavaScript, introduce some of the constructs and features provided by functional programming. In many cases, the repetitive code of JavaScript leads to some poor coding. If you use functional programming, you can avoid these problems. In addition, a more graceful callback can be written using a functional programming style.

Because functional programming uses a completely different way of organizing programs, programmers who are accustomed to using imperative paradigms may find that functional programming is a bit difficult to learn. In this article, you'll learn some examples of how to use functional styles to write good, graceful code in JavaScript. I will discuss:

Functional programming concepts, including anonymous functions, different methods of calling functions, and ways to pass functions as arguments to other functions.

The use of functional concepts includes: Extended array ordering, graceful code generated by dynamic HTML, and the application of series functions.
Functional Programming Concepts

Please tell everyone. Please submit this to:


Digg

Slashdot

Many developers know how to encode in a language that describes how to specify a method of solving a problem by describing how to do it. For example, to write a function that calculates the factorial, I can write a loop to describe the program, or use recursion to find the product of all numbers. In both cases, the process of calculation is described in detail in the program. Listing 1 shows a possible C code that calculates 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 differs significantly from this principle. In functional programming, the question "what" needs to be described. Functional programming language is also called declarative language. The same program that calculates the factorial can be written as the product of all numbers to N. The typical functional program that calculates the factorial looks like the example in Listing 2 shows.


Listing 2. Factorial of functional style

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

The second statement indicates that you want to get a list of the first n numbers starting from 1 (take n [1 ...] ), and then find their product, 1 as the primitive. This definition differs from the previous example in that there is no loop or recursion. It is like the arithmetic definition of the factorial function. Once you understand the meaning of library functions (take and FOLDR) and tags (list notation []), writing code is easy and readable.

With only three lines of Miranda code, you can write routines that use breadth-first or depth-first traversal for each node of the N-fork tree, depending on the parameters, and that 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 Haskell on the. NET platform. In other cases, some of the existing languages borrow some of the concepts in functional programming languages. Examples of this borrowing are the iterators and continuation in some C + + implementations, and some of the 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 see some of the more interesting apps.

anonymous functions

In JavaScript, you can write anonymous functions or functions that do not have 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);
} (a);
alert (sum);

Using functions as values

You can also use a function as a value. You can also have some variables that are assigned to functions. 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 ());


In the example above 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 from anywhere.

Different ways to call functions

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


Listing 7. A typical function application

Alert ("Hello, world!");

Or


Listing 8. Using functions as expressions

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

So you can also write the following code:


Listing 9. After defining a function, you can use it immediately

(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 the operation on the parameter. Although in the example in Listing 8, there is a function name that is directly enclosed in parentheses, this is not the case when you use it in the same way as shown in Listing 9.

Passing functions as arguments to other functions

You can also pass functions as arguments to other functions. While this is not a new concept, this concept is used extensively in subsequent examples. The function arguments can be passed, 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

Executes the last alert statement output a value of size 12.

Using Functional concepts

The previous section describes some programming concepts that use functional styles. The examples given do not contain all the concepts, and they have no precedence in importance, just some concepts related to this discussion. Here's a quick summary of the functional styles in JavaScript:

The function does not always require a name.
Functions can be assigned to variables just 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 the effective use of these concepts to write graceful JavaScript code. (with JavaScript functional style, you can do a lot of things beyond this scope of discussion.) )

Extended Array Ordering
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 sorting method of the 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 need, use the example in Listing 12.


Listing 12. The 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 is passed along with its definition to the sort function to complete the sort operation. Use this function:

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

Graceful code for dynamically generated HTML
In this example, you'll see how to write graceful code that dynamically generates HTML from an array. Tables can be generated based on the values obtained from the data. Alternatively, you can use the contents of the array to generate a sorted and unordered list. You can also create 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 normal 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 ways 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 the new function fold. You can now use the function in any of the arrays defined later.

The application of series function
Consider the following scenario: you want to use a set of functions as a callback function. For this purpose, the Window.settimeout function is used, which has two parameters. The first parameter is a function that is called after the number of milliseconds that the second parameter represents. 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);

You can also use the code extension in Listing 16 if you want to invoke a callback after invoking a callback when handling an event. This may be an exercise you need to do yourself, and now your interest is lit up.


Back to top of page


Conclusion

Functional programming in JavaScript can be applied in many areas to perform everyday activities in a graceful manner. The examples in this article describe only a few cases. If you find the right scenario for functional programming and apply these concepts, you will have more understanding and can increase your degree of elegance.

Writing graceful JavaScript with functional programming techniques

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.