lodash中的函数组合
lodash中组合函数flow()或者flowRight(),他们都可以组合多个函数;flow()是从左到右运行;flowRight()是从右到左运行。
const _ = require('lodash')
// 把数组中的最后一个函数取出来;并把它转成首字母大写。
const reverse = arr => arr.reverse()
const first = arr => arr[0]
const toUpper = s => s.charAt(0).toUpperCase() + s.slice(1)
const f = _.flowRight(toUpper, first, reverse)
console.log(f(['one', 'two', 'three']));
模拟lodash中的flowRight实现
const compose = (...args) => value => args.reverse().reduce((acc, fn) => fn(acc), value)
函数组合要满足结合律;所谓结合律就是:我们既可以把g和h组合;还可以把f和g组合,结果都是一样的;let isTrue = compose(f, compose(g, h)) == compose(compose(f, g), h) 结果是true
lodash中的fp模块
lodash中的fp模块提供了实用的对函数式编程友好的方法;这些方法是不可变得;柯里化的、如果参数是多个的话,函数在前;数据之后
例如:
// lodash 中的map方法是数据在前;函数在后
const _ = require('lodash')
let res = _.map(['a', 'b', 'c'], _.toUpper)
console.log(res);
console.log(_.split('Hello World', ' '));
// fp模块 函数优先;数据放后面;如果只穿了一个函数;则会生成一个函数;等待传入数据
const fp = require('lodash/fp')
let a = fp.map(fp.toUpper, ['a', 'b', 'c'])
console.log(a);
console.log("********************");
console.log(fp.split(' ', 'Hello World'));
console.log(fp.split(' ')('Hello World'));
// 要把字符串 NEVER SAY DIE 转换成 never-say-die
const compose = fp.flowRight(fp.join('-'), fp.map(fp.toLower), fp.split(' '))
console.log(compose('NEVER SAY DIE'));
let a1 = ['23', '4', '10']
console.log(a1.map(x => parseInt(x)));
point free 模式
point free 模式就是把运算的过程合成一个函数;而在这个函数中是不需要指明我们需要的参数
// 案例
// Hello World => hello_world
const fp = require('lodash/fp')
// replace第三个参数是需要替换的字符串
const f = fp.flowRight(fp.replace(/\s+/g, '_'), fp.toLower)
console.log(f('Hello World'));```