当前位置:网站首页>JS to realize coritization

JS to realize coritization

2022-06-11 03:34:00 Love to eat virgin fruit

currying

Definition : The method of transforming a multi parameter function into a single parameter function .

  • js Implement the corellization of the function free version

Example :curryingadd(2)(1, 3, 4)(2, 3)(3)(4, 6)(7, 98);

function curryingadd() {
    
    let args = Array.from(arguments);
    let innerAdd = function () {
    
      let argsinner = Array.from(arguments);
      //  If there are no internal parameters at this time, that is  f(...arg)()  Just return the value directly 
      if (argsinner.length == 0) {
    
        return args.reduce((prev, cur) => {
    
          return prev + cur;
        });
      } else {
    
        //  We use closures here   because args It's externally defined   So you can accumulate and store variables during recursion 
        args.push(...arguments);
        return innerAdd;
      }
    };
    innerAdd.toString = function () {
    
      return args.reduce((prev, curr) => {
    
        return prev + curr;
      }, 0);
    };
    return innerAdd;
  }
   let res = curryingadd(2)(1, 3, 4)(2, 3)(3)(4, 6)(7, 98);//133
   let res1= curryingadd(2)(1, 3, 4)(2, 3)(3)(4, 6)(7, 98)();
   
  • js Realize the coritization of function version

Such as :curry(add1)(1, 2)(3)

function add1(x, y, z) {
    
return x + y + z;
}

const curry = (fn, ...args) => 
//  The number of function parameters can be directly determined by the number of functions .length Property to access 
args.length >= fn.length //  This judgment is crucial !!!
//  The parameter passed in is greater than or equal to the original function fn The number of parameters , Then execute the function directly 
? fn(...args)
/** *  The parameter passed in is smaller than the original function fn Number of parameters  *  Then continue to curry the current function , Returns a that accepts all parameters ( Current and remaining parameters )  Function of  */
: (..._args) => curry(fn, ...args, ..._args);

console.log(curry(add1)(1, 2)(3));//6

Challenge Gengwen 100 God ----- the second day

原网站

版权声明
本文为[Love to eat virgin fruit]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/162/202206110325340845.html