function/curry.jsjavascript
/**
* 将多参数函数转换为可分批传参的柯里化函数。
* @function curry
* @memberof module:function
* @param {Function} fn 目标函数
* @param {...*} arg 初始参数
* @returns {Function} 柯里化后的函数
* @throws {TypeError} fn 不是函数时抛出
*/
function curry(fn, ...arg) {
if (typeof fn !== 'function') throw new TypeError('fn must be a function')
const _this = this
const args = Array.from(arguments).slice(1)
// fn.length 属性指明函数的形参个数。
const len = fn.length
return function () {
const _args = Array.from(arguments)
args.push(..._args)
if (args.length < len) {
return curry.call(_this, fn, ...args)
}
return fn.apply(_this, args)
}
}
export default curry