- 纯函数的代表—- Lodash:
lodash 是一个纯函数的功能库,提供了模块化、高性能以及一些附加功能。提供了对数组、数字、对象、字符串、函数等操作的一些方法
const _ = require('lodash')
_.first()
_.last()
_.toUpper()
_.reverse()
_.each()
- Lodash中的柯里化 — curry:
- _.curry(func)
- 功能:创建一个函数,该函数接收一个或多个 func的参数,如果 func 所需要的参数都被提供则执行 func 并返回执行的结果。否则继续返回该函数并等待接收剩余的参数。
- 参数:需要柯里化的函数
- 返回值:柯里化后的函数 ```javascript const _ = require(‘lodash’) function getSum (a, b, c) { return a + b + c }
- _.curry(func)
// 定义一个柯里化函数 const curried = _.curry(getSum)
// 如果输入了全部的参数,则立即返回结果 console.log(curried(1, 2, 3)) // 6
//如果传入了部分的参数,此时它会返回当前函数,并且等待接收getSum中的剩余参数 console.log(curried(1)(2, 3)) // 6 console.log(curried(1, 2)(3)) // 6
3. lodash中的函数组合方法: flowRight(从右到左执行), flow(从左到右执行)
```javascript
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'])) // THREE