关于es6:实现一个compose函数

5次阅读

共计 1171 个字符,预计需要花费 3 分钟才能阅读完成。

纯函数和柯里化很容易写出洋葱代码 h(g(f(x)))。洋葱代码的嵌套问题使得咱们的保护更加艰难。这与咱们选用函数式编程的开发初衷是相违反的,在这种状况下函数组合的概念就应运而生。
函数组合能够让咱们把细粒度的函数重新组合生成一个新的函数
上面这张图示意程序中应用函数解决数据的过程,给 fn 函数输出参数 a,返回后果 b。能够想想 a 数据通过一个管道失去了 b 数据。

当 fn 函数比较复杂的时候,咱们能够把函数 fn 拆分成多个小函数,此时多了两头运算过程产生的 m 和 n。
上面这张图中能够设想成把 fn 这个管道拆分成了 3 个管道 f1, f2, f3,数据 a 通过管道 f3 失去后果 m,m。再通过管道 f2 失去后果 n,n 通过管道 f1 失去最终后果 b

fn = compose(f1, f2, f3)
b = fn(a)

函数组合

函数组合 (compose):如果一个函数要通过多个函数解决能力失去最终值,这个时候能够把两头过程的函数合并成一个函数。函数就像是数据的管道,函数组合就是把这些管道连接起来,让数据穿过多个管道造成最终
函数组合默认是从右到左执行
函数的组合要满足结合律 (associativity):
咱们既能够把 g 和 h 组合,还能够把 f 和 g 组合,后果都是一样的

lodash 中组合函数 flow() 或者 flowRight(),他们都能够组合多个函数
flow() 是从左到右运行
flowRight() 是从右到左运行,应用的更多一些

const _ = require('lodash')
const toUpper = s => s.toUpperCase()
const reverse = arr => arr.reverse()
const first = arr => arr[0]
const f = _.flowRight(toUpper, first, reverse)
console.log(f(['one', 'two', 'three']))

模仿实现

const reverse = (arr) => arr.reverse();
const first = (arr) => arr[0];
const toUpper = (s) => s.toUpperCase();

// 从左往右执行就不须要执行 reverse 操作
function compose(...args) {return function (value) {return args.reverse().reduce(function (acc, fn) {return fn(acc);
    }, value);
  };
}

const es6_Compose =
  (...args) =>
  (value) =>
    args.reverse().reduce((acc, fn) => fn(acc), value);

const f = es6_Compose(toUpper, first, reverse);
console.log(f(["one", "two", "three"]));
正文完
 0