前端常用方法——compose和reduce

前端常用方法——compose和reduce

场景

​ 之前学习的时候看到一个这样的方法

const compose = (arr) => {
  return arr.reduce((a,b) => (...args) => a(b(...args)))
}

当时看的时候文章说他是 不断嵌套调用方法,比如
const a = (num) => {}
const b = (num) => {}
const c = (num) => {}

const fn = compose([a,b,c])
fn(num)
// 实际效果就是
a(b(c(num)))

​ 当时不是特别理解,这次看到reduce了就想结合着一块看下,彻底搞懂这个方法

reduce用法
// reduce方法适用于数组,可以接受两个参数,第一个是函数方法,用于从开始到末尾的方法调用等等,第二个是默认值,加入默认值时可以从默认值开始依次与数组开始到结束进行逻辑处理

console.log([1,2,3,4].reduce((a,b) => {
  return a + b
},2))

// 这样就会返回12
模拟reduce
// 知道了reduce的方法后,我们可以根据模拟一个简易版的reduce方法(不考虑校验等等,比较基础的方法),
// 他可以接受两个参数,第一个是fn,函数方法,第二个是默认值。当有默认值时优先从默认值开始调用,没有默认值就从数组第0项开始。依次采用fn调用数组每一项

// 模拟代码如下
Array.prototype.mockReduce = function (fn,initialValue) {
  const arr = this
  let startIndex = initialValue ? 0 : 1
  let acc = initialValue || arr[0]
  for(let i = startIndex; i < arr.length; i++) {
    acc = fn(acc,arr[i])
  }
  return acc
}

console.log([1,2,3,4].mockReduce((a,b) => {
  return a + b
},2))
// 12
compose方法
// 模拟实现了reduce后,发现对compose方法有了新的感悟,采用箭头方式不容易看清楚,将其变成function的方法
const compose = (arr) => {
  return arr.reduce(function(a,b){
    return function(...args) {
      return a(b(...args))
    }            
  })
}

// 结合mockReduce,我们可以知道每次调用时都会拿到两项逻辑处理后的值,可以模拟下
const a = (num) => {
  return num + 1
}
const b = (num) => {
  return num * 2
}
const c = (num) => {
  return num - 1
}
const fn = compose([a,b,c])
fn(2) // 3

// 内部reduce时,首先从a,b开始,加入中间变量 temp
const temp = function(...args){return a(b(...args))}
// temp为前两项逻辑处理后的值,再处理第三项
const fn = temp(c)
// 这样就相当于
const fn = (...args) => ((function(...args)(return a(b(...args))))(c(...args)))
====>  const fn = (...args) => a(b(c(...args)))

这样就得到了嵌套使用的compose
总结

​ 这个方法是看redux的时候看到的,当时看到的是简易版的实现,就是采用反转数组,之后依次调用嵌套方法的方式就行了,虽然这个方法不怎么通俗易懂,但是它设计的真的很巧妙,写起来也非常简洁明了~

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值