Skip to content

柯里化

一次柯里化

js
// 实现一次 curry 的实现
function onceCurry(fn, ...arg1) {
	return function(...arg2) {
    return fn.apply(this, arg1.concat(arg2))
  }
}

function onceCurry(fn, ...arg1) {
  return (...arg2) => fn(...arg1, ...arg2)
}
js
function sum(a, b) {
	return a + b
}

let sumCurry = onceCurry(sum, 1, 2)
sumCurry() // 3
sumCurry = onceCurry(sum, 1)
sumCurry(2) // 3
sumCurry = onceCurry(sum)
sumCurry(1, 2) // 3

多次柯里化

根据 当前参数的个数 和 离完成执行还需要传入的参数个数,判断是否执行,还是返回新的柯里化

js
function curry(fn, length) {
  const len = length || fn.length
  return (...arg) => 
    arg.length >= len ?
      fn(...arg) :
      curry(onceCurry(fn, ...arg), len - arg.length)
}

使用

js
function sum(a,b,c,d){
	return a + b + c + d;
}
const sumCurrying = curry(sum)

console.log( sumCurrying(1)(2)(3)(4) ) // 10
console.log( sumCurrying(1, 2)(3, 4) ) // 10