js-读书笔记-函数式编程-惰性链

// 惰性链
function LazyChain(obj) {
  let isLC = (obj instanceof LazyChain) // 组合链,抽取调用链和目标对象
  this._calls = isLC ? [...obj._calls] : []
  this._target = isLC ? obj._target : obj
}
// 封装了一些行为的函数通常被称为thunk
LazyChain.prototype.invoke = function(methodName, ...args) {
  this._calls.push(function(target) {
    let meth = target[methodName]
    return meth.apply(target, args)
  })
  return this
}
LazyChain.prototype.force = function() {
  return this._calls.reduce((target, thunk) => {
    return thunk(target)
  }, this._target)
}
LazyChain.prototype.tap = function(fun) {
  this._calls.push(function(target) {
    fun(target)
    return target
  })
  return this
}

let ret = new LazyChain([2, 1, 3]).invoke('sort').force()
console.log(ret)

ret = new LazyChain([2, 1, 3]).invoke('concat', [8, 7, 5, 6]).invoke('sort').invoke('join', ' ').force()
console.log(ret)

let deferredSort = new LazyChain([2, 1, 3]).invoke('sort').tap(x => console.log('alert'))
deferredSort.force()

ret = new LazyChain(deferredSort).invoke('toString').force()
console.log(ret)



惰性链和promise的区别:

高度耦合关联的任务、低耦合的任务。同步和异步。

缺点:

紧耦合对象的set和get(命令/查询)分离、尴尬命名问题
调用之间改变传递的共同引用

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值