-
Notifications
You must be signed in to change notification settings - Fork 0
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
部分柯里化函数题 #2
Comments
请写出一个柯里化其他函数的函数 function curry(fn,arg){
???
return ???
}
var abc = function(a, b, c) {
return [a, b, c];
};
var curried = curry(abc);
curried(1)(2)(3);
// 输出 => [1, 2, 3]
curried(1, 2)(3);
// 输出 => [1, 2, 3]
curried(1, 2, 3);
// 输出 => [1, 2, 3] Answer:
function curry(fn,arg){
var thisArg = arg ? arg : []
return function(){
// 判断总共传入参数是否达标,未达标继续柯里化过程
if(thisArg.length + [...arguments].length < 3){
return curry(fn,[...thisArg,...arguments])
}else{
// 达到指定长度调用 abc 函数
return fn.apply(null,[...thisArg,...arguments])
}
}
}
var abc = function(a, b, c) {
return [a, b, c];
};
var curried = curry(abc);
curried(1)(2)(3);
// 输出 => [1, 2, 3]
curried(1, 2)(3);
// 输出 => [1, 2, 3]
curried(1, 2, 3);
// 输出 => [1, 2, 3] 对 function curry(fn,arg){
return (function rez(fn,arg){
var thisArg = arg ? arg : []
return function(){
// 判断总共传入参数是否达标,未达标继续柯里化过程
if(thisArg.length + [...arguments].length < 3){
return rez(fn,[...thisArg,...arguments])
}else{
// 达到指定长度调用 abc 函数
return fn.apply(null,[...thisArg,...arguments])
}
}
})(fn,arg)
} |
实现一个sum函数, function sum(){
let args = [...arguments]
function _sum(){
args = [...args,...arguments]
return _sum
}
_sum.valueOf = function(){
return args.reduce((a,b)=> a + b,0)
}
return _sum
}
console.log(sum(1,2).valueOf()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The text was updated successfully, but these errors were encountered: