Front-end-learning-to-organize-notes icon indicating copy to clipboard operation
Front-end-learning-to-organize-notes copied to clipboard

函数柯里化

Open Chocolate1999 opened this issue 4 years ago • 4 comments

Chocolate1999 avatar Jan 21 '21 09:01 Chocolate1999

// 普通的add函数
function add(x, y) {
    return x + y
}

// Currying后
function curryingAdd(x) {
    return function (y) {
        return x + y
    }
}

add(1, 2)           // 3
curryingAdd(1)(2)   // 3

HearLing avatar Jan 22 '21 09:01 HearLing

实际上就是把add函数的x,y两个参数变成了先用一个函数接收x然后返回一个函数去处理y参数。 就是只传递给函数一部分参数来调用它,让它返回一个函数去处理剩下的参数。 用处:

  1. 参数复用
  2. 提前确认
  3. 延迟运行

HearLing avatar Jan 22 '21 09:01 HearLing

function curry(fn, args = []) {
    return function(){
        let rest = [...args, ...arguments];
        if (rest.length < fn.length) {
            return curry.call(this,fn,rest);
        }else{
            return fn.apply(this,rest);
        }
    }
}
//test
function sum(a,b,c) {
    return a+b+c;
}
let sumFn = curry(sum);
console.log(sumFn(1)(2)(3)); //6
console.log(sumFn(1)(2, 3)); //6

Chocolate1999 avatar Jan 25 '21 15:01 Chocolate1999

function curry(fn, args = []) {
  console.log([...arguments]) // 空\1\1,2
  return function () {
    console.log([...arguments])//1\2\3
    console.log([...args])//空\1\1,2
    let rest = [...args, ...arguments]
    if (rest.length < fn.length) {
      return curry.call(this, fn, rest)
    } else {
      return fn.apply(this, rest)
    }
  }
}
//test
function sum(a, b, c) {
  return a + b + c
}
let sumFn = curry(sum)
console.log(sumFn(1)(2)(3)) //6
console.log(sumFn(1)(2, 3)) //6

HearLing avatar Jan 25 '21 15:01 HearLing