Open Hongbusi opened 2 years ago
// 简单实现组合函数
const compose =
(...args: any[]) =>
values => {
return args.reverse().reduce((prev, curr) => curr(prev), values);
};
const reverse = (arr: any[]) => arr.reverse();
const first = (arr: any[]) => arr[0];
const toUpper = (value: string) => value.toUpperCase();
const flowRight = compose(toUpper, first, reverse);
console.log('flowRight', flowRight(['a', 'b', 'flow']));
function compose(...fns) {
let res
return function(...args) {
fns.forEach((fn) => {
if (!res) {
res = fn(...args)
} else {
res = fn(res)
}
})
return res
}
}
/**
* composeRight (参数从右往左)
* compose (参数从左往右)
*/
export function composeRight(...fns) {
return function (x) {
return fns.reduceRight((v, f) => f(v), x);
};
}
export function compose(...fns) {
return function (x) {
return fns.reduce((v, f) => f(v), x);
};
}