参考:前端经典面试题解密-add(1)(2)(3)(4) == 10到底是个啥? - 掘金
函数柯里化:是把接受多个参数的函数转变为接受一个单一参数的函数,并且返回接受余下的参数且返回结果的新函数的技术。
解释起来就是,先将一个接受多个参数的函数转变为接受一个单一参数的函数,在这个函数中根据条件来返回自己去继续接受下一次传入的参数,或者将累计的参数传入原函数执行并将结果返回。
函数柯里化有两种不同的场景,
1、参数个数定长的函数
2、参数个数不定长的函数
定长:
// 定长参数
function add (a, b, c, d) {
return [
...arguments
].reduce((a, b) => a + b)
}
function currying (fn) {
let args = []
return function _c (...newArgs) {
// 合并参数
args = [...args,...newArgs]
// 判断当前参数集合args的长度是否 < 目标函数fn的需求参数长度
if (args.length < fn.length) {
// 继续返回函数
return _c
} else {
// 返回执行结果
return fn.apply(this, args)
}
}
}
let addCurry = currying(add)
let total = addCurry(1)(2)(3)(4) // 同时支持addCurry(1)(2, 3)(4)该方式调用
console.log(total) // 10
不定长:
function add (...args) {
return args.reduce((a, b) => a + b)
}
function currying (fn) {
let args = []
return function _c (...newArgs) {
if (newArgs.length) {
args = [...args,...newArgs]
return _c
} else {
return fn.apply(this, args)
}
}
}
let addCurry = currying(add)
// 注意调用方式的变化
console.log(addCurry(1)(2)(3)(4, 5)())