Principle and Process of Currization Realization of JavaScript Function

  • 2021-10-11 17:29:45
  • OfStack

Brief introduction
When we read the Vue source code, we will find that the function Currization is used in its _ update instance, (createPatchFunction method). If you are interested, you can

Go and have a look.

Currization (Currying) is a technique for transforming a function that accepts multiple parameters into a function that accepts a single 1 parameter (the first parameter of the original function) and returns a new function that accepts the remaining parameters and returns the result.

In "Mostly adequate guide", Currying is summed up by passing function 1 only some arguments to call it, and having it return a function to handle the remaining arguments.

Currying is a kind of realization of functional programming, which can bring convenience to our programming. What exactly does the Currying function look like? Look down, let's write a Corey function according to its concept

Realization


//  How to achieve  add(1,2) === add(1)(2)
let add = (...args) => {
  return args.length === 1 ? a => a + args[0] : args[0] + args[1]
}

This seems to be close to Corrigenization at one point, but it is not really Currying. We should do add (1, 2, 3,,,) = = = currying (add) (1, 2, 3,,,) to be a real Corrigenization function. OK, let's keep going.


let add = (...args) => args.reduce((a,b)=>a+b)
 
let currying = (fn)=>{
  return function(...args){
    return fn.apply(this, args)
  }
}
// add(1,2,3,,,) === currying(add)(1,2,3,,,)

Some people play like this, you can refer to it


let currying = (fn) => {
  var args = [].slice.call(arguments, 1)
  return function() {
    var newArgs = args.concat([].slice.call(arguments))
    return fn.apply(this, newArgs)
  }
}
 
let addCurry = currying(add, 1, 2);
addCurry() // 3
 
addCurry = currying(add, 1);
addCurry(2) // 3
 
addCurry = currying(add);
addCurry(1, 2) // 3

In fact, this implementation method uses the principle of closure, so we have time to make a comparison.

Analysis

As you can see, in fact, Coriolis function is not difficult. If we want to use it in our development, we need to spend a little time ~

Reference: https://github.com/FIGHTING-TOP/FE-knowlodge-base/issues/4


Related articles: