What is functional coriolism

Time:2022-5-24

What is function curry

Each time a function is called, it accepts only some parameters and returns a function to process the remaining parameters until all parameters are passed.
for instance:

const add = (x, y,z) => x + y+z;
add(1, 2,3);
//Use Coriolis
const add = x => y =>z => x + y +z;
add(1)(2)(3);

What is the effect of coritization?

It mainly has three functions: parameter reuse, early return and delayed execution

  • Parameter reuse: take the above add function as an example. As long as a parameter Z is passed in, the calculation result is the result of 1 + 2 + Z. the two parameters 1 and 2 can be reused directly.
  • Early return and delayed execution: each time a function is called, it only accepts some parameters and returns a function to process the remaining parameters (early return here) until all parameters are passed (delayed execution here)

Interview sharing

Write a summation function to support these three writing methods:add(1, 2, 3);add(1, 2)(3);add(1)(2, 3);

//The number of parameters can be passed directly through the function The length property is accessed. If the number of parameters passed in is greater than or equal to the number of parameters of the original FN, the function will be executed directly. If the number of parameters passed in is less than the number of parameters of the original FN, the curry of the current function will continue and a function that accepts all parameters (current parameters and remaining parameters) will be returned
const curry = (fn,...args)=> args.length>=fn.length?fn(...args):(..._args)=>curry(fn,...args,..._args)

function add1(x,y,z){
  return x+y+z
}
const add = curry(add1);
console.log(add(1, 2, 3));
console.log(add(1)(2)(3));
console.log(add(1, 2)(3));
console.log(add(1)(2, 3));