JavaScript 深度剖析---02函数式编程范式
2021-04-20 本文已影响0人
丽__
函数组合
- 纯函数和柯里化很容易写出洋葱代码
- 获取数组的最后一个元素在转换成大写字母 .toUpper(.first(_.reverse(array)))
![](https://img.haomeiwen.com/i24717104/945f6a87890eb331.png)
- 函数组合可以让我们把细粒度的函数重新组合成一个新的函数
管道
下面这张图表示程序中使用函数处理数据过程,给fn函数输入参数a,返回结果b,
![](https://img.haomeiwen.com/i24717104/5fb1a79b0d6a6ed7.png)
当fn函数比较复杂的时候,我们可以吧函数fn拆分为多个小函数,此时多了中间运算过程产生的m和n.
下面这张图中可以想象成把fn这个管道拆分成了3个管道 f1,f2,f3,数据a通过管道f3得到结果m,m在通过f2得到结果n,n再通过管道f1得到最终的结果b
![](https://img.haomeiwen.com/i24717104/e9f7c24bc3fc8cd4.png)
fn = compose(f1,f2,f3)
b = fn(a)
函数组合
- 函数组合(compose)的概念:如果一个函数要经过多个函数处理才能得到最终的值,这个时候可以把中间的处理过程的函数合并成一个函数
- 函数就像是数据的管道,函数组合就是把这些管道连接起来,让数据穿过多个管道行程最终的结果
- 函数组合默认是从右到左执行
// 函数组合演示
function compose(f, g) {
return function (value) {
return f(g(value))
}
}
// 反转
function reverse(array) {
return array.reverse()
}
// 获取第一个
function first(array) {
return array[0]
}
const last = compose(first, reverse);//先执行的放在最后(先反转,在获取第一个)
console.log(last([1,2,3,4]));
lodash种的组合函数
- lodash种的组合函数
- lodash中的组合函数flow()或者flowRight(),他们都可以组合多个函数
- flow()是从左到右运行
- flowRight() 是从右往左运行,使用的更多一些
// lodash中的函数组合方法 _.flowRight()
const _ = require('lodash')
const reverse = arr => arr.reverse()
const first = arr => arr[0]
const toUpper = s => s.toUpperCase()
// 从右到左执行
const f = _.flowRight(toUpper, first, reverse)
console.log(f(['one','two','three']))
// 原理实现
function compose(...args) {
return function (value) {
return args.reverse().reduce(function (acc, fn) {
return fn(acc)
}, value)
}
}
// ES6写法
const compose = (...args) => value => args.reverse().reduce((acc, fn) => fn(acc), value)
const reverse = arr => arr.reverse()
const first = arr => arr[0]
const toUpper = s => s.toUpperCase()
const f = compose(toUpper, first, reverse)
console.log(f(['one', 'two', 'three']))
// 输出 THREE
函数的结合律
- 函数的组合要满足结合律
- 既可以把g和h组合,还可以把f和g组合,结果一样
//结合律(associativity)
let f = compose(f,g,h)
let associative = compose(compose(f,g),h) == compose(f,compose(g,h))
//true
// 函数组合要满足结合律
const _ = require('lodash')
// const f = _.flowRight(_.toUpper,_.first,_.reverse)
// const f = _.flowRight(_.flowRight(_.toUpper,_.first),_.reverse)
const f = _.flowRight(_.toUpper,_.flowRight(_.first,_.reverse))
console.log(f(['one','two','three']));
// 输出 THREE
函数组合调试
- 如何调试组合函数
// 函数组合 调试
const _ = require('lodash')
const trace = _.curry((tag, v) => {
console.log(tag, v)
return v
})
const split = _.curry((sep, str) => _.split(str, sep))
const join = _.curry((sep, array) => _.join(array, sep))
const map = _.curry((fn, array) => _.map(array, fn))
const f = _.flowRight(join('-'), trace('map 之后'), map(_.toLower), trace('split 之后'), split(' '))
console.log(f('NEVER SAY DIE'))
//输出结果为:
split 之后 [ 'NEVER', 'SAY', 'DIE' ]
map 之后 [ 'never', 'say', 'die' ]
never-say-die
Lodash 中的FP模块
- fp(函数式编程的模块)
- lodash的fp模块提供了使用的对函数式编程友好的方法
- 提供了不可变 auto-curried iteratee-first data-last 的方法
//lodash模块
const _ = require('lodash')
_.map(['a','b','c'],_toUpper)
//结果 ['A','B','C']
_.map(['a','b','c'])
//结果 ['a','b','c']
_.split('hello World',' ')
//lodash/fp模块
const fp = require('lodash/fp')
fp.map(fp.toUpper,['a','b','c'])
fp.map(fp.toUpper)(['a','b','c'])
fp.split(' ','Hello World')
fp.split(' ')('Hello World')
// fp模块
const fp = require('lodash/fp')
const f = fp.flowRight(fp.join('-'),fp.map(fp.toLower),fp.split(' '))
console.log(f('NEVER SAY DIE'))
lodash-map方法
// lodash 和lodash/fp模块中的map方法的区别
const _ = require('lodash')
console.log(_.map(['23', '8', '10'], parseInt));
const fp = require('lodash/fp')
console.log(fp.map(parseInt,['23','8','10']))
Point Free
point free: 我们可以把数据处理的过程定义成与数据无关的合成运算,不需要用到代表数据的那个参数,只要把简单的运算步骤合成到一起,在使用这种模式之前我们需要定义一些辅助的基本运算函数。
- 不需要指明处理过程
- 只需要合成运算过程
- 需要定义一些辅助的基本运算函数
const f = fp.flowRight(fp.join('-'),fp.map(_.toLower),fp.split(' '))
// point free
const fp = require('lodash/fp')
const f = fp.flowRight(fp.replace(/\s+/g, '_'), fp.toLower)
console.log(f('Hello World'));
- 案例
// 把一个字符串中的首字母提取并且转换成大写,使用. 作为分隔符
// world wild web ===> W.W.W
const fp = require('lodash/fp')
const firstLetterToUpper = fp.flowRight(fp.join('.'),fp.map(fp.first),fp.map(fp.toUpper), fp.split(' '))
//优化
const firstLetterToUpper = fp.flowRight(fp.join('.'), fp.map(fp.flowRight(fp.first, fp.toUpper)), fp.split(' '))
console.log(firstLetterToUpper('world wild web'));