[1,2,3,4,5].map(x => x * 2).filter(x => x > 5).reduce((p,n) => p + n);
const store = applyMiddleware(...middlewares)(createStore)(reducer, initialState)
函数可以当做参数传递给其他函数,也可以作为函数的返回值返回(高阶函数)。
// 函数柯里化
function curry(fn, args){
args = args || []
return function(...params){
let _args = [...args, ...params]
if(_args.length < fn.length){
return curry(fn, _args)
}
return fn.apply(this, _args)
}
}
function sum(a, b, c){
return a+b+c
}
// 自由组合参数
const currySum = curry(sum)
console.log(currySum(1)(2)(3)) //6
console.log(currySum(1)(2,3)) //6
console.log(currySum(1,2)(3)) //6
export const pipe: any =
(...fns: Promise<Function>[]) =>
(input: any) =>
fns.reduce((chain: Promise<Function>, func: Function | Promise<Function> | any) => chain.then(func), Promise.resolve(input));
export const compose: any =
(...fns: Promise<Function>[]) =>
(input: any) =>
fns.reduceRight((chain: Promise<Function>, func: Function | Promise<Function> | any) => chain.then(func), Promise.resolve(input));
需求背景介绍
private pipe = (...args: any) => {
return (result: any, config?: any) => {
return args.reduce((acc: any, fn: any) => fn(acc, config), result);
};
};
// 扩展方向替换
private handleExpand(expandConf: string) {
return (conf: any) => {
if (expandConf) {
conf.expandDirection = expandConf;
}
return conf;
};
}
// 父行/父列替换
private handleParentCell(columnParentCell: any, rowParentCell: any) {
return (conf: any) => {
if (columnParentCell?.parentSelectType) {
conf.columnParentCell = columnParentCell;
}
if (rowParentCell?.parentSelectType) {
conf.rowParentCell = rowParentCell;
}
return conf;
};
}
// 条件属性追加
private handleCondition(conditionBatchConf: any) {
return (conf: any) => {
conf.conditionConf = this.mergeCondition(conf?.conditionConf || [], conditionBatchConf);
return conf;
};
}
// 批量修改
private mergeCondition(c1: any, c2: any) {
for (let j = 0; j < c1.length; j++) {
// 批量删除
if (
c1[j]?.batchFlag &&
this.batchConf.conditionConf?.find((item: any) => item.uuid === c1[j]?.uuid) &&
!c2.find((item: any) => item.uuid === c1[j]?.uuid)
) {
c1.splice(j, 1);
}
}
for (let j = 0; j < c1.length; j++) {
for (let i = 0; i < c2.length; i++) {
// 如果字段已存在则替换
if (c2[i]?.uuid === c1[j]?.uuid) {
c1.splice(j, 1);
}
}
}
return [...c1, ...c2];
}
//...
//...
let handles: Array<any> = [];
if (cell?.dataConf?.cellType === "文本") {
handles = [
this.handleExpand(conf.expandDirection),
this.handleParentCell(conf.columnParentCell, conf.rowParentCell)
];
} else if (cell?.dataConf?.cellType === "字段" || cell?.dataConf?.cellType === "公式") {
handles = [
this.handleExpand(conf.expandDirection),
this.handleParentCell(conf.columnParentCell, conf.rowParentCell),
this.handleFormat(conf.dataFormatConf),
this.handleFilter(conf.cellFilterConf),
this.handleCondition(conf.conditionConf)
];
}
if (handles.length > 0) {
const mergeConf = this.pipe(...handles)(JSON.parse(JSON.stringify(cell.dataConf)));
//...
}