Lodash中的FP模块
- 我们在使用函数组合解决问题的时候,会使用到lodash中提供的一些方法,但如果这些方法有多个参数的时候,我们需要对这些方法进行柯里化的处理,我们需要重新去包装这些方法,稍微有些麻烦,接下来我们来介绍lodash中的fp模块
- lodash/fp
- lodash 的 fp 模块提供了实用的对函数式编程友好的方法
- 提供了不可变 auto-curried、iteratee-first、data-last
const _ = require('lodash')
console.log(_.map(['a', 'b', 'c'], _.toUpper))
console.log(_.map(['a', 'b', 'c']))
console.log(_.split('Hello World', ' '))
const fp = require('lodash/fp')
console.log(fp.map(fp.toUpper, ['a', 'b', 'c']))
console.log(fp.map(fp.toUpper)(['a', 'b', 'c']))
console.log(fp.split(' ', 'Hello World'))
console.log(fp.split(' ')('Hello World'))
- lodash 与 lodash/fp 在实际使用时的区别
const _ = require('lodash')
const map = _.curry((fn, array) => _.map(array, fn))
const split = _.curry((sep,str) => _.split(str,sep))
const join = _.curry((sep, array) => _.join(array, sep))
const f = _.flowRight(join('-'), map(_.toLower), split(' '))
console.log(f('NEVER SAY DIE'))
const fp = require('lodash/fp')
const f = fp.flowRight(fp.join('-'), fp.map(fp.toLower), fp.split(' '))
console.log(f('NEVER SAY DIE'))
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
function f (world) {
return world.toLowerCase().replace(/\s+/g, '_')
}
const fp = require('lodash/fp')
const f = fp.flowRight(fp.replace(/\s+/g, '_'), fp.toLower)
fp.replace
console.log(f('Hello World'))
Point Free 案例
const fp = require('lodash/fp')
const f = fp.flowRight(fp.join('. '), fp.map(fp.flowRight(fp.first, fp.toUpper)), fp.split(' '))
console.log(f('world wild web'))