compose函数和pipe函数

compose函数

1.将需要嵌套执行的函数平铺
2.嵌套执行指的是,一个函数的返回值将作为另一个函数的参数

实现函数式编程中的Pointfree,使我们专注于转换而不是数据

像下面这段简单的代码:

let calculate = x => (x + 10) * 10;
console.log(calculate(10));

也可以像下面这样写:

let add = x => x + 10;
let multiply = y => y * 10;
console.log(multiply(add(10)));

提高代码的复用性,则可以如下:

let add = x => x + 10;
let multiply = y => y * 10;
let compose = (f,g) => {
    return function(x){
        return(f(g(x)));
    }
}

let calculate = compose(multiply,add);
console.log(calculate(10));

而想要多个函数嵌套运算,实现通用的compose函数,则可以如下:

let add = x => x + 10;
let multiply = y => y * 10;
let compose = function(){
    let args = [].slice.call(arguments);
    return function(x){
        return args.reduceRight(function(res, cb){
            return cb(res);
        },x)
    }
}
let calculate = compose(multiply,add);
console.log(calculate(10));

更简便的写法,如下:

let add = x => x + 10;
let multiply = y => y * 10;
//es6写法
const compose = (...args) => x => args.reduce((res, cb) => cb(res), x);
let calculate = compose(multiply,add);
console.log(calculate(10));

compose函数的执行方向是从右往左执行,而pipe函数则相反

pipe函数

let add = x => x + 10;
let multiply = y => y * 10;
//es6写法
const compose = (...args) => x => args.reduceLeft((res, cb) => cb(res), x);
let calculate = compose(multiply,add);
console.log(calculate(10));

你可能感兴趣的:(compose函数和pipe函数)