Functional Programming makes JS more elegant

Source: Internet
Author: User
Function Type Programming Language It has been in the academic field for a long time, but historically they have no rich tools and libraries available for use. With the emergence of Haskell on the. NET platform, functional programming has become more popular. Some traditional programming languages, such as C ++ and JavaScript, introduce some structures and features provided by functional programming. In many cases, JavaScript is repeated. Code Resulting in some poor encoding. If you use functional programming, you can avoid these problems. In addition, you can use the functional programming style to write more elegant callbacks. Function programming only describes Program You do not need to use temporary variables to save the intermediate results. The key is to capture "what and why", rather than "how to do ". Compared with procedural programming that focuses on executing continuous commands, functional programming focuses on the definition of functions rather than the implementation of state machines. Large-scale knowledge management system applications have benefited a lot from the functional programming style, because functional programming simplifies development. 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 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: functional programming concepts, including 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. Many developers know how to encode the concept of functional programming in languages that specify a solution to the problem 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. Process-style factorial program code 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. Function-style factorial program code factorial n, where n <= 0: = 1 factorial N: = foldr * 1 take n [1 ..] the second statement specifies the list of the first n numbers starting from 1 (take n [1 ..]), then we can 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. 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: Typical function code program code function Sum (x, y, z) {return (x + y + Z );} then the corresponding anonymous function should look as follows: the code function (x, y, z) {return (x + y + Z);} of the Code Program of the anonymous function program should use it, you need to write the following code: Application anonymous function code program code var sum = function (x, y, z) {return (x + y + Z, 3); alert (SUM); using a function as a value can also be used as a value. You can also assign values to variables of functions. In the last example, you can also perform the following operations: Use the Function Assignment Program code program code var sum = function (x, y, z) {return (x + y + Z);} alert (sum (1, 2, 3); in the preceding example, the value assigned to the sum variable is the function definition itself. In this way, sum becomes a function that can be called anywhere. Different methods of calling a function JavaScript allows two methods to call a function. Program code alert ("Hello, world! "); Or program code (alert) (" Hello, world! "); So you can also write the following code: After defining a function, you can immediately use its program code (function (x, y, z) {return (x + y + Z)}) (1, 2, 3); you can write a function expression in parentheses and pass it to the parameter to perform operations on the parameter. Although in the example in listing 8, there are function names directly included in brackets. 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. Pass the function as a parameter and apply the Code 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. 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 function does not always need a name. 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 .) To sort the extended array, write 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. Compare function program code function (x, y) {return X. Date-y. date;} to obtain the required function, use the example in listing 12. Arr. Sort (function (x, y) {return X. Date-y. Date ;}); 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. In this example, you can see how to write beautiful code and generate HTML dynamically from arrays. 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. Generate dynamic HTML common code program code var STR = ''; For (VAR I = 0; I <arr. length; I ++) {var element = arr [I]; STR + =... HTML generation code ...} document. write (STR); general method of generating dynamic HTML by using program code 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. The applications of series functions consider the following situation: you want to use a group of functions as Callback functions. 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. Program code window. setTimeout (function () {alert ('first! '); Alert ('second! ') ;}, 5000); a better way to call a series of functions program code 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.

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.