介绍

什么是函数式编程?

什么是纯函数?

  • 相同输入得到相同输出
  • 没有副作用

举例, splice改变原数组,不是纯函数。slice不改变原数组, 是纯函数。

什么是函数式编程?

编程有两种方式

  • 命令式
  • 声明式

函数式编程需要倚重一些工具函数( 如 map filter ruduce find 等数组函数和 curry compose 等工具函数 )

什么是柯里化?

https://github.com/mqyqingfeng/Blog/issues/42
柯里化是一种架构多个参数的函数转换成一系列使用一个或多个参数的函数的技术。
例如 实现函数add(1)(2, 3)(4).getValue()

什么是组合?

将不同的纯函数组合成一个新的函数
作用:组合函数, 将函数串联起来执行。
总结:

  • compose参数是函数, 返回一个函数
  • 第一个函数接受参数, 其他函数接受的是上一个函数的返回值。(注意,第一个函数的参数是多元的, 其他函数的参数是一元的)
  • compose函数接受的函数, 执行方向自右向左,初始函数放在参数的最右边什么是函子?

库ramda

教程 https://www.ruanyifeng.com/blog/2017/03/ramda.html

组合

  1. const R = require('ramda')
  2. const greeting = (name) => `hello ${name}`;
  3. const toUpper = (str) => str.toUpperCase();
  4. const fn = R.compose(toUpper, greeting);
  5. console.log(fn('Lucy'));
  6. // HELLO LUCY

环境搭建

  1. yarn init -y
  2. npm install ramda -S

库lodash/fp

https://github.com/lodash/lodash/wiki/FP-Guide

组合

  1. const { compose } = require('lodash/fp')
  2. const greeting = (name) => `hello ${name}`;
  3. const toUpper = (str) => str.toUpperCase();
  4. const fn = compose([toUpper, greeting]);
  5. console.log(fn('Lucy'));
  6. // HELLO LUCY

compose等价于flowRight

  1. const _ = require('lodash')
  2. const greeting = (name) => `hello ${name}`;
  3. const toUpper = (str) => str.toUpperCase();
  4. const fn = _.flowRight([toUpper, greeting]);
  5. console.log(fn('Lucy'));
  6. // HELLO LUCY

环境搭建

  1. yarn init -y
  2. npm install lodash -S

参考:
https://mp.weixin.qq.com/s/I6vBgC50D4Pnq_ZTw7_xwA