daily-share
daily-share copied to clipboard
reduce处理一段很灵性的代码(2020-1-29)
reduce 方法处理一段代码
class SyncWaterfallHook {
constructor(arg) {
this.tasks = [] // 存储监听函数
}
tap(name, task) {
this.tasks.push(task)
}
call(...args) {
// 让监听函数的一个函数的返回结果是第一个监听函数的值
let [first, ...others] = this.tasks
let ret = first(...args)
others.reduce((a, b) => {
return b(a) // 这个reduce 很灵性
}, ret)
}
}
const hooks = new SyncWaterfallHook()
hooks.tap('react', function(name) {
console.log('react', name)
return 'ok'
})
hooks.tap('node', function(name) {
console.log('node', name)
})
hooks.call('yaogengzhu')