美文网首页
Redux源码阅读_2

Redux源码阅读_2

作者: 晴窗细语 | 来源:发表于2020-08-08 15:18 被阅读0次

compose.ts

从右到左来组合多个函数,是reduce函数的一个应用实现。

首先仍然是重载了多个参数的函数声明,区别主要是传入参数个数。

export default function compose<F extends Function>(f: F): F

/* two functions */
export default function compose<A, T extends any[], R>(
  f1: (a: A) => R,
  f2: Func<T, A>
): Func<T, R>

/* three functions */
export default function compose<A, B, T extends any[], R>(
  f1: (b: B) => R,
  f2: (a: A) => B,
  f3: Func<T, A>
): Func<T, R>

/* four functions */
export default function compose<A, B, C, T extends any[], R>(
  f1: (c: C) => R,
  f2: (b: B) => C,
  f3: (a: A) => B,
  f4: Func<T, A>
): Func<T, R>

/* rest */
export default function compose<R>(
  f1: (a: any) => R,
  ...funcs: Function[]
): (...args: any[]) => R

export default function compose<R>(...funcs: Function[]): (...args: any[]) => R

然后是主要代码:

export default function compose(...funcs: Function[]) {
  if (funcs.length === 0) {
    // infer the argument type so it is usable in inference down the line
    return <T>(arg: T) => arg
  }

  if (funcs.length === 1) {
    return funcs[0]
  }

  return funcs.reduce((a, b) => (...args: any) => a(b(...args)))
}

可以看到compose函数主要是调用了reduce方法来实现迭代。

相关文章

  • Redux源码阅读_2

    compose.ts 从右到左来组合多个函数,是reduce函数的一个应用实现。 首先仍然是重载了多个参数的函数声...

  • redux 源码阅读

    redux 源码阅读 首先从 redux 的官方示例来看 redux 的作用 这样简单一看的话, redux 感觉...

  • redux源码阅读

    Redux 是可预测的状态管理框架,它很好的解决多交互,多数据源的诉求。 三大原则: 单一数据源:整个应用的sta...

  • redux源码阅读——applyMiddleware

    redux源码——applyMiddleware 相关源码展示 applyMiddleware源码 compose...

  • redux源码阅读记录

    标签(空格分隔): redux javascirpt createStore 导语: 最近在看 redux,也看了...

  • Redux源码阅读_3

    combineReducers.ts 函数重载声明 首先是对combineReducers函数的重载,重载了三个函...

  • Redux源码阅读_4

    applyMiddleware.ts 函数重载声明 首先是对applyMiddleware函数的重载,重载了七个函...

  • redux源码阅读笔记

    砖头搬完了,找点乐趣,记得之前看vuex的源码.. 挺有意思,没有记录..现在忘光光.. 这一年一直写reac...

  • redux源码分析

    这篇文章会很长。redux源码读起来并不困难。读懂redux的源码有利于更好的使用redux。但是react-re...

  • 重读redux源码

    之前5.1假期的时候,有去读了下redux的源码,当时感触很深,今天重新梳理遍redux的源码:从源码中的src文...

网友评论

      本文标题:Redux源码阅读_2

      本文链接:https://www.haomeiwen.com/subject/tlzfdktx.html