高阶函数就是传参有函数作为参数的函数。比如很多数组方法都是高阶函数,map、filter、reduce、forEach等等。
而在业务开发中,使用高阶函数可以:
1.降低代码耦合度,便于复用,
2.代码结构清晰,便于团队合作等等
接下来就来看一看常用的高阶函数叭。
柯里化
const curry = (fn, ...args) =>
// 函数的参数个数可以直接通过函数数的length属性来访问
// 这个判断很关键!!!
args.length >= fn.length
// 传入的参数大于等于原始函数fn的参数个数,则直接执行该函数
? fn(...args)
// 传入的参数小于原始函数fn的参数个数时
// 则继续对当前函数进行柯里化,返回一个接受所有参数(当前参数和剩余参数) 的函数
: (..._args) => curry(fn, ...args, ..._args);
//测试
function sumFn(a, b, c) {
return a + b + c;
}
var sum = curry(sumFn);
console.log(curry(sumFn)(2)(3)(5));
console.log(curry(sumFn)(2, 3, 5));
console.log(curry(sumFn, 2, 3, 5));
console.log(curry(sumFn, 2, 3, 5, 1, 1, 1));
console.log(curry(sumFn, 2, 3)(5));
console.log(curry(sumFn)(2)(3, 5));
console.log(curry(sumFn)(2, 3)(5));
console.log(curry(sumFn)(1)(2)(3));
组合
//compose组合
//1.reduceRight
function compose(...fns) {
return function (x) {
return fns.reduceRight(function (arg, fn) {
return fn(arg)
}, x)
}
}
//2.循环写法
// function compose(...fns) {
// return function (x) {
// let res = x;
// for (let i = fns.length - 1; i >= 0; i--) {
// res = fns[i](res);
// }
// return res;
// }
// }
//测试
let fn1 = function (x) {
return x + 2;
}
let fn2 = function (x) {
return x + 3;
}
let fn3 = function (x) {
return x + 4;
}
console.log(fn3(fn2(fn1(1))));
console.log(compose(fn3, fn2, fn1)(1));
管道
//pipeline管道
//compose反过来,从左往右
function pipeline(...fns) {
return function (X) {
return fns.reduce((arg, fn) => {
return fn(arg)
}, x)
}
}
记录记录!