Impulsive JavaScript Item 19 uses High-Order functions, javascript

Source: Internet
Author: User
Tags types of functions

Impulsive JavaScript Item 19 uses High-Order functions, javascript

This series serves as the Reading Notes for objective JavaScript.

 

Do not hide the name of a higher-order function. In fact, higher-order functions only represent two types of functions:

  1. Functions that accept other functions as parameters
  2. Function whose return value is a function

 

With this definition, you may find that you have used them. A typical example is the callback function passed in when processing some events.

 

Another typical application scenario is the Array-type sort function, which accepts a function as the basis for comparison during sorting:


[3, 1, 4, 1, 5, 9].sort(function(x, y) {if (x < y) {return -1;}if (x > y) {return 1;}return 0;}); // [1, 1, 3, 4, 5, 9]


Use higher-order functions to make code clearer and more clean. When performing operations on data of the set type, you can consider using them. for example, you can convert the following for loop:


var names = ["Fred", "Wilma", "Pebbles"];var upper = [];for (var i = 0, n = names.length; i < n; i++) {upper[i] = names[i].toUpperCase();}upper; // ["FRED", "WILMA", "PEBBLES"]

Use the map function introduced in ES5:


var names = ["Fred", "Wilma", "Pebbles"];var upper = names.map(function(name) {return name.toUpperCase();});upper; // ["FRED", "WILMA", "PEBBLES"]

Of course, in a non-ES5 compatible browser, if you want to use higher-order functions such as map, you can use underscore or lodash. They provide a lot of Array and Object operations.

 

When there are many repeated fragments in the code, we can consider using high-level functions to refactor them. For example, the following code contains three similar codes: the first segment is used to generate the alphabet, the second segment is used to generate the number table, and the last segment is used to generate a fixed-length random string:


var aIndex = "a".charCodeAt(0); // 97var alphabet = "";for (var i = 0; i < 26; i++) {alphabet += String.fromCharCode(aIndex + i);}alphabet; // "abcdefghijklmnopqrstuvwxyz"var digits = "";for (var i = 0; i < 10; i++) {digits += i;}digits; // "0123456789"var random = "";for (var i = 0; i < 8; i++) {random += String.fromCharCode(Math.floor(Math.random() * 26)+ aIndex);}random; // "bdwvfrtp" (different result each time)

Different parts of the above three cases can be encapsulated into a callback and then processed using a higher-order function. The higher-order function extracts the public parts of the three cases:


function buildString(n, callback) {var result = "";for (var i = 0; i < n; i++) {result += callback(i);}return result;}

The above three situations can be implemented as follows:


var alphabet = buildString(26, function(i) {return String.fromCharCode(aIndex + i);});alphabet; // "abcdefghijklmnopqrstuvwxyz"var digits = buildString(10, function(i) { return i; });digits; // "0123456789"var random = buildString(8, function() {return String.fromCharCode(Math.floor(Math.random() * 26) + aIndex);});random; // "ltvisfjr" (different result each time)

Obviously, this implementation method can cover more possibilities, because the changed part is represented by callback. At the same time, this method also conforms to the encoding best practices. When the loop part needs to change, you only need to modify one place.

 

Summary:

  1. Higher-order functions are functions that use other functions as parameters or return functions as return values.
  2. Learning to use map and other methods, learning to use the lodash or underscore Library
  3. Find repeated code snippets in the Code and use high-order functions to refactor them.

 

 







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.