Last active
August 23, 2020 17:01
-
-
Save njleonzhang/72077c1a1f6704e175c2d4ead81fdb3a to your computer and use it in GitHub Desktop.
compose
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function fn1(num) { | |
console.log('fn1', num) | |
return num | |
} | |
function fn2(num) { | |
console.log('fn2', num) | |
return num | |
} | |
function fn3(num) { | |
console.log('fn3', num) | |
return num | |
} | |
function fn4(num) { | |
console.log('fn4', num) | |
return num | |
} | |
function compose(funs) { | |
// 返回的 composed, 必然是一个参数为 num 的函数 | |
return (num) => funs.reduce((previous, current) => current(previous), num) | |
} | |
let composed = compose([fn1, fn2, fn3, fn4]) | |
composed(1) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function fn1(next){ | |
console.log('fn1') | |
next() | |
console.log('end fn1') | |
} | |
function fn2(next){ | |
console.log('fn2') | |
next() | |
console.log('end fn2') | |
} | |
function fn3(next){ | |
console.log('fn3') | |
next() | |
console.log('end fn3') | |
} | |
function fn4(next){ | |
console.log('fn4') | |
next() | |
console.log('end fn4') | |
} | |
function compose(funs) { | |
return oNext => funs.reduceRight((previous, current) => () => current(previous), oNext)() | |
} | |
let composed = compose([fn1, fn2, fn3, fn4]) | |
composed(() => console.log('oNext called')) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment