Using functional programming technique to write graceful javascript_javascript skills

Source: Internet
Author: User
Tags function definition reserved sorts

Level: Primary

Shantanu Bhattacharya (shantanu@justawordaway.com), Chief advisor, Siemens information Systems Limited

July 20, 2006

functional or declarative programming is a very powerful programming method that is gradually becoming popular in the software industry. This article will introduce some of the relevant functional programming concepts and provide examples of effective use of these concepts. The authors explain how to write graceful code using JavaScript (TM), which enables JavaScript to import functional programming constructs and features.
--> --> -->

Brief introduction

Functional programming languages have existed for quite some time in the academic field, but historically they have not been rich in tools and libraries to use. With the advent of Haskell on the. NET platform, functional programming becomes 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 causes some poor coding. If you use functional programming, you can avoid these problems. In addition, a more graceful callback can be written using functional programming styles.

Functional programming

Functional programming only describes actions performed on program input, and you do not have to use temporary variables to save intermediate results. The point is to capture "what and why," rather than "how". In contrast to procedural programming that focuses on executing sequential commands, functional programming focuses on the definition of a function rather than the implementation of a state machine.

Large-scale knowledge management system applications benefit from the use of functional programming styles because functional programming simplifies development.

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 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 finds their product, and 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. Applying 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. A typical function application
				
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
The
first writes 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 an array object of type. 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 the array type of
  • JavaScript accepts optional arguments, which 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. Common code for generating 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 Array the prototype property of the 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. To achieve this, you will use the window.setTimeoutfunction, 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. Call 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 invoke 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.

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.