[JavaScript] Higher-order functions - function currying

What are higher order functions?

Higher-order functions: Functions that operate on other functions, passing them as arguments, or returning a function. A function is a higher-order function if it meets either of the following two specifications.
1. If the parameter received by function A is a function, then A can be called a high-order function.
2. If the return value of function A is still a function, then A can be called a high-order function.

Example one:

	function test1(back) {
    
    
      console.log("我接收到的参数back是一个函数");
      back() //调用参数函数
    }
    function callback() {
    
    
      console.log("我是函数callback");
    }
    test1(callback)

insert image description here

Example two:

	function test2() {
    
    
      return function back() {
    
    
        console.log("我是返回值,我是个函数!");
      }
    }
    test2()()

insert image description here

Common higher-order functions

Array.prototype.reduce

The reduce() method executes a reducer function provided by you (in ascending order) on each element in the array, aggregating its results into a single return value.
Receive parameters: arr.reduce(callback[, initialValue])

arr.reduce(function(accumulator, currentValue, currentIndex, array), initialValue)

reduceThe method receives 1 callbackfunction as the first parameter, and 1 optional parameter initialValue.
At the same time callbackthe function has a maximum of 4 parameters.

  • accumulatorThe accumulator accumulates the return value of the callback; it is the accumulated value returned the last time the callback was called. initialValueIts default value is if provided initialValue, otherwise it is the first value of the array.
  • currentValueThe element currently participating in the calculation.
  • currentIndex(Optional) The array subscript of the element currently participating in the calculation.
  • array(Optional) The array currently participating in the operation.
  • initialValue(Optional) Initial value for the accumulator. When there is no accumulator, the value of the accumulator is currentValue for the first time

Note: An error will be thrown when the reduce method is called on an empty array with no initial value set.

Example:

	// arr.reduce(function (accumulator, currentValue, currentIndex, array) {
    
    
    //  return accumulator + currentValue
    // }, initialValue)

	let arr = [1, 2, 3, 4, 5, 6, 7]
    let sum = arr.reduce(function (a, b) {
    
    
      return a + b
    }, 10)
    console.log(sum);

insert image description here

Array.prototype.filter

filter()method creates a new array whose elements are checked by checking all elements in the specified array that meet the criteria. Returns an empty array if the test fails. filter()Empty arrays are not checked and the original array is not mutated.

filterCalls the function once for each element in the array callback, creating a new array with all elements such that callbackreturns a value trueof or equivalent to . It will only be called on indexes that have been assigned, and will not be called on indexes that have been deleted or have never been assigned. Elements that fail the test are skipped and not included in the new array.truecallbackcallback

Example:

	let array = ['apple', 'banana', 'car', 'dog', 'egg']
    let result = array.filter(function (data) {
    
    
      return data.length <= 3
    })
    console.log(result);

insert image description here

In addition, there are Promise, setTimeout, arr.map()etc.

function currying

Function currying (Currying): through the method of continuing to return the function through the function call, it realizes the function encoding form that receives parameters multiple times and finally processes them uniformly. That is, the technique of transforming a function that accepts multiple parameters into a function that accepts a single parameter (the first parameter of the original function), and returns a new function that accepts the remaining parameters and returns the result.

Function currying is the process of changing a function that originally accepted two parameters into a new function that accepts one parameter. The new function returns a function that takes the original second parameter as a parameter. These functions will not be evaluated immediately. Instead, it saves the incoming parameters through closures, and does not evaluate them until they are really needed, reducing code redundancy and realizing function reuse, which is an important application of js functional programming.
Currying does not call the function, but only converts the function, which refers to converting a function from a callable fn(x, y, z, …) to a callable fn(x)(y)(z)…

Example:

  <script>
    // 正常写法:
    function sum(a, b, c) {
    
    
      return a + b + c
    }
    const result = sum(1, 2, 3)
    console.log(result);

    // 函数柯里化演示:
    function sum2(a) {
    
    
      return (b) => {
    
    
        return (c) => {
    
    
          return a + b + c
        }
      }
    }
    const result2 = sum2(1)(2)(3)
    console.log(result2);
  </script>

insert image description here

Comprehensive case presentation:

<script type="text/babel">
    class Login extends React.Component {
    
    
      state = {
    
    
        username: '',
        password: ''
      }
      // saveFormData 函数就是一个高阶函数+柯里化函数:调用的返回值依然是一个函数,多次接收参数最后统一处理的函数编码形式。
      saveFormData = (dataType) => {
    
    
        return (event) => {
    
    
          console.log(event.target.value);
          this.setState({
    
    
            [dataType]: event.target.value
          })
        }
      }
      handleSubmit = (event) => {
    
    
        event.preventDefault();
        const {
    
     username, password } = this.state
        alert(`你输入的用户名是:${
      
      username},你输入的密码是:${
      
      password}`)
      }
      render() {
    
    
        return (
          <form action="" onSubmit={
    
    this.handleSubmit}>
            用户名: <input type="text" onChange={
    
    this.saveFormData('username')} /> <br /><br />
            密码: <input type="password" onChange={
    
    this.saveFormData('password')} name="password" id="" /> <br /><br />
            <button>登录</button>
          </form>
        )
      }
    }
    ReactDOM.createRoot(document.getElementById('test')).render(<Login />)
  </script>

If wrong, please correct me!

Guess you like

Origin blog.csdn.net/aDiaoYa_/article/details/131556590