function curry(fn, arr) {
// 空数组保底
arr = arr || []
return function () {
// 1. 函数参数转数组,可以用展开写法
var args = [].slice.call(arguments)
// 2. 之前的参数和上一次的参数用concat组合起来
var arg = arr.concat(args)
console.log(arg.length)
// 3. 判断参数长度是否达到原函数参数的长度,达到了就调用函数,否则递归调用curry
return arg.length >= fn.length
? fn.apply(null, arg)
: curry(fn, arg)
}
}
// ES6
const curry = (fn, arr = []) => (...args) => (
arg => arg.length >= fn.length
? fn(...arg)
: curry(fn, arg)
)([...arr, ...args])
function add(a, b, c, d) {
return a + b + c + d
}
const a = curry(add)
console.log(a(1)(2, 10)(3))
console.log(a(1)(2)(3)(4))
console