Skip to content

Instantly share code, notes, and snippets.

@njleonzhang
Last active August 23, 2020 17:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save njleonzhang/72077c1a1f6704e175c2d4ead81fdb3a to your computer and use it in GitHub Desktop.
Save njleonzhang/72077c1a1f6704e175c2d4ead81fdb3a to your computer and use it in GitHub Desktop.
compose
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)
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