compose

compose函数接受一系列函数作为参数,在第一个参数函数执行完之后,将结果作为参数传入第二个参数函数执行。

compose和pipe的区别

compose的参数执行顺序是从右到左,pipe是从左到右

效果

// compose
const compose = (...args: any[]) => {
    return (ctx: any) => {
        let prevRes = ctx
        for (let index = args.length - 1; index >= 0; index--) {
            const fn = args[index];
            prevRes = fn(prevRes)
        }
        return prevRes
    }
}
 
const add = (a: number) => a + 1
const multiply = (x: number) => x * 10
 
const fn = compose(add, multiply)
const fn2 = compose(multiply, add)
console.log(fn(1), fn2(1)); // 11 20
 
// pipe
 
const pipe = (...args: any[]) => {
    return (ctx: any) => {
        let res = ctx
        for (let index = 0; index < args.length; index++) {
            const fn = args[index];
            res = fn(res)
        }
        return res
    }
}
// 使用reduce重写
const pipe2 = (...args: any[]) => {
    return (ctx: any) => {
        return args.reduce((res, cb) => cb(res), ctx)
    }
}
 
const add2 = (a: number) => a + 1
const multiply2 = (x: number) => x * 10
 
const fn3 = pipe2(add2, multiply2)
const fn4 = pipe2(multiply2, add2)
console.log(fn3(1), fn4(1));