解题1:
function currying(fn, length) {
length = length || fn.length; // 注解 1
return function (...args) { // 注解 2
return args.length >= length // 注解 3
? fn.apply(this, args) // 注解 4
: currying(fn.bind(this, ...args), length - args.length) // 注解 5
}
}
解题2:
const currying = fn =>
judge = (...args) =>
args.length >= fn.length
? fn(...args)
: (...arg) =judge(...args, ...arg)
注解说明:
- 注解 1:第一次调用获取函数 fn 参数的长度,后续调用获取 fn 剩余参数的长度
- 注解 2:currying 包裹之后返回一个新函数,接收参数为 …args
- 注解 3:新函数接收的参数长度是否大于等于 fn 剩余参数需要接收的长度
- 注解 4:满足要求,执行 fn 函数,传入新函数的参数
- 注解 5:不满足要求,递归 currying 函数,新的 fn 为 bind 返回的新函数(bind 绑定了 …args 参数,未执行),新的 length 为 fn 剩余参数的长度
解题3:
使用了一个闭包完成了这个效果
function add(...num) {
let res = 0 //第一次调用函数时生成一个闭包来存储结果
num.forEach(item => res += item) //遍历输入参数加到res上
let ret = function (...num) {
num.forEach(item => res += item)
return ret
}
ret.toString = function () {
return res
}
ret.valueOf = function () {
return res
}
return ret
}
console.log(add(1)); // 1
console.log(add(1)(2)); // 2
console.log(add(1)(2)(3)); // 6
console.log(add(1)(2)(3,7)(4,5,6));// 28
解题4 ?:
:point_down:~~~~ 欢迎在下方评论补充你的答案,一起来学习~:pushpin:
更多内容