柯理化函数
函数柯里化,就是可以将一个接受多个参数的函数分解成多个接收单个参数的函数的技术,直到接收的参数满足了原来所需的数量后,才执行原函数
//求和
const sumFn = (...args) => {
return args.reduce((a,b) =>{
return a + b;
})
};
//排序
const sortFn = (...args) => {
return args.sort((a,b) => a - b);
}
let currying = function(fn){
const args = []; //接收所有传递的参数
return function result(...rest){
//剩下的参数
if(rest.length === 0){
return fn(...args);
}else{
args.push(...rest);
return result;
}
}
}
console.log(currying(sumFn)(1)(2)(3)()); //6
console.log(currying(sumFn)(1,2)(3,4)(5)()); //15
console.log(currying(sumFn)(1)(2,3,4,5)(6)()); //21
console.log(currying(sortFn)(1)(3)(2)(6,4)(5)());
<script>
//fn(1,2,3)(4,5)(6)(7,2,3,4,5,6,7);
//fn(1,2,3,4,5,6,7,8,9)
// function fnSum(a,b){
// return a + b;
// }
// function fnSum(a){
// return function(b){
// return a + b;
// };
// }
// alert(fnSum(2)(2));
//求和
function fnSum(... args){
return args.reduce((prev,next) => {
return prev + next;
})
}
//排序
function fnSort(... args){
return args.sort((a,b) => {
return b - a;
})
}
//最大值
function fnMax(... args){
return Math.max(... args);
}
//最小值
function fnMin(... args){
return Math.min(... args);
}
//数组去重
function fnNoRepeatArr(... args){
return [... new Set(args)];
}
//柯理化函数
////fn(fnSum)(1,2,3)(4,5)(6)(7,2,3,4,5,6,7)();
function currying(fn){
//准备一个数组,准备存放所有的参数
let arr = [];
//返回一个函数
return function result(... args){
//接收每一次调用时传递的参数
if(args.length === 0){
return fn(...arr);
}else{
arr.push(... args);
return result;
}
}
}
console.log(currying(fnSum)(1,2)(3,4,5)(6,7,8,9)());
console.log(currying(fnSort)(5,4,6)(3)(7,2,8,1,9)());
console.log(currying(fnMax)(5,4,6)(8,3,4,2,0)(9,1,2,4)());
console.log(currying(fnMin)(5)(2)(4)(2)(1)(6)());
console.log(currying(fnNoRepeatArr)(3,2)(1,1,2,2,3,4)(6,5,6,6,3,3,4)(9,9,5,4,2)());
</script>