Open haizhilin2013 opened 3 years ago
function sum(a){ return(b)=>{ return (c)=>{ return a+b+c } } } console.log(sum(1)(2)(3))
let result=0 const curryScore = function(fn){ let score = [] return function(){ if(arguments.length === 0){ fn.apply(null,score) }else{ score = score.concat(Array.prototype.slice.call(arguments,0)) } } } const addScore = curryScore(function(){
result = Array.prototype.slice.call(arguments,0).reduce(function(prev,next){
return prev+next
})
function add(...args){
return args.reduce((a, b) => a + b)
}
function currying(fn){ // 返回一个函数用于接收参数 let score = [] return function inner(...args){
//判断 如果调用函数中没有传入参数则 返回结果 否则返回自身
if(args.length === 0){
return fn.apply(this,score)
}else{
score = [...score,...args]
return inner
}
}
} let addCurry = currying(add) console.log(addCurry(1)(2)(3)())
const curry = function(fn) {
const arity = fn.length; // 获取参数个数
return function $curry(...args) {
if (args.length === arity) {
return fn.apply(this, args);
} else {
return function(...args2) {
return $curry.apply(this, args.concat(args2));
}
}
}
}
const test = function(a, b, c) {
return a + b + c;
}
const curriedTest = curry(test);
const result = curriedTest(1)(2)(3);
console.log('result:', result); // 6
const result2 = curriedTest(1)(2, 3);
console.log('result2:', result2); // 6
第711天 实现一个函数柯里化
1142
3+1官网
我也要出题