1. 高阶函数
在数学和计算机科学中,高阶函数是至少满足下列一个条件的函数:
- 接受一个或多个函数作为输入;(filter、map、reduce)
- 输出一个函数。
2. 函数组合
函数组合就是将两个或两个以上的函数组合生成一个新函数的过程:
// 示例1:f 和 g 都是函数,而 x 是组合生成新函数的参数。
const composeFn = function (f, g) {
return function (x) {
return f(g(x));
};
};
reduce的高阶用法
// 示例1:
let res = [1,2,3].reduce((x,y)=>{
return x+y
}, 5)
执行顺序:第一次5作为x,1作为y;后面以此类推
函数组合借助reduce和闭包实现
// 示例1:
function lowerCase(input) {
return input && typeof input === "string" ? input.toLowerCase() : input;
}
function upperCase(input) {
return input && typeof input === "string" ? input.toUpperCase() : input;
}
function trim(input) {
return typeof input === "string" ? input.trim() : input;
}
function split(input, delimiter = ",") {
return typeof input === "string" ? input.split(delimiter) : input;
}
// 组合函数
function compose(...funcs) {
return function (x) {
return funcs.reduce(function (arg, fn) {
return fn(arg);
}, x);
};
}
const trimLowerCaseAndSplit = compose(trim, lowerCase, split);
trimLowerCaseAndSplit(" a,B,C "); // ["a", "b", "c"]