Talk about higher order functions in JS

"Higher order function" is a term we often meet. Its English name is "higher order function". It's quite mysterious for novices. Today, let's talk about lower higher-order function s.

Definition

Functions that receive functions as arguments or return functions

In the Vernacular:

  1. First, it's a function
  2. Parameter or return value is a function

For example

Here are two examples to cover the above definition. One is the higher-order function with the receiving function as the parameter, and the other is the higher-order function with the return function.

Example 1: function as parameter

We define a function called evaluatesToFive that takes two parameters: the first is a number, and the second is a function. In the function evaluatesToFive, pass parameter one (number) into parameter two (function)

function evaluatesToFive(num, fn) {
  return fn(num) === 5;
}

Scenarios used:

function divideByTwo(num) {
  return num / 2;
}

evaluatesToFive(10, divideByTwo);
// true

evaluatesToFive(20, divideByTwo);
// false

Haha, although the function itself is not very useful, but for describing higher-order functions, it is very easy to understand.

Example 2: return function

In this case, we create the function multiplyBy, which takes a number as an argument and returns a new function

function multiplyBy(num1) {
  return function(num2) {
    return num1 * num2;
  };
}

Usage scenario:

const multiplyByThree = multiplyBy(3);
const multiplyByFive = multiplyBy(5);

multipyByThree(10); // 30

multiplyByFive(10); // 50

It's a little bit of a feeling that we can achieve more specific goals by generating new functions.

More complex application examples

In this example, we create a function to check whether the registration information of new users can pass the verification rule:

  • Over 18 years old
  • Password length greater than 8
  • Agree to user agreement

The registration information of new users is as follows:

const newUser = {
  age: 24,
  password: 'some long password',
  agreeToTerms: true,
};

Next, let's create three validation functions by returning true, otherwise false

function oldEnough(user) {
  return user.age >= 18;
}

function passwordLongEnough(user) {
  return user.password.length >= 8;
}

function agreeToTerms(user) {
  return user.agreeToTerms === true;
}

Next, the protagonist comes on stage. We need to create a higher-order function to complete all the verification at once. The first parameter is the new user registration information, and the remaining parameters are the three validation functions we created above. In the function body, perform the verification successively:

function validate(obj, ...tests) {
  for (let i = 0; i < tests.length; i++) {
    if (tests[i](obj) === false) {
      return false;
    }
  }
  return true;
}

Use:

const newUser1 = {
  age: 40,
  password: 'tncy4ty49r2mrx',
  agreeToTerms: true,
};

validate(newUser1, oldEnough, passwordLongEnough, agreeToTerms);
// true

const newUser2 = {
  age: 40,
  password: 'short',
  agreeToTerms: true,
};

validate(newUser2, oldEnough, passwordLongEnough, agreeToTerms);
// false

So far, it's great. Keep looking and see how we can improve

Continued evolution

In the above, when we use the validate function, we need to pass in multiple validation functions (oldEnough, passwordLongEnough, agreeToTerms), which violates the principle of least knowledge (students who are interested can learn about it Minimum knowledge principle ), see how we can continue to improve it:

function createValidator(...tests) {
  return function(obj) {
    for (let i = 0; i < tests.length; i++) {
      if (tests[i](obj) === false) {
        return false;
      }
    }
    return true;
  };
}

The createValidator function is awesome. It takes any number of functions as parameters, and the return value is also a function. So this createValidator is also a higher-order function.

Use:

const userValidator = createValidator(
  oldEnough,
  passwordLongEnough,
  agreeToTerms
);

userValidator(newUser1); // true
userValidator(newUser2); // false

Do you see any doorways? Use the function createValidator to generate a more specific validation function userValidator, and then use userValidator to verify the registration information of new users. What a wonderful high order function! You can learn another term of currification!

epilogue

In this article, we have discussed the higher-order function in JS. Do not think that the higher-order function is just an interview question. The popular higher-order components in the front-end frame are also referenced from higher-order functions. High order functions are often used in our daily development. When used well, many complex business logic can be decoupled, which is very meaningful for code readability and maintainability! The knowledge of closure is also used in this paper. Have you found it? Don't let your knowledge lie in the interview questions forever!

All of the above are my own thoughts. You are welcome to share them. By the way, please pay attention to them. Partners who have problems or need to learn materials can click Java learning sharing group Let's talk

 

Tags: Programming Java

Posted on Mon, 09 Mar 2020 04:22:43 -0400 by xadmin