Appearance
函数式编程
函数式编程以函数为核心,侧重于数据的流转,只关心什么样的输入从而得到什么样的输出结果
特点:
- 函数式一等公民
- 说函数和其他数据类型一样处于平等的地位,可以作为变量赋值给其他变量、可以作为参数进行传递、可 以作为其他函数的返回值等,正是由于函数的特殊地位我们才能去实现函数式编程。
纯函数
如果函数的调用参数相同,则永远返回相同的结果。它不依赖于程序执行期间函数外部任何状态或数据的变化,必须只依赖于其输入的参数(相同的输入,必须得到相同的输出)。
ts
// 纯函数
const add = (a, b) => a + b
let total = add(1, 2)
console.log(total)
副作用
函数本身不依赖函数外部也不会修改函数外部的数据,如 this,对象入参
- 引用透明
引用透明就是指输入相同的参数永远会得到相同的输出
- 数据不可变
其主要指的是引用类型的入参,如果需要修改,不要修改参数本身,而是重新生成一份进行修改 (immer.js)
js
// 数据可变 修改入参params
const normalParams = params => {
if (!params.key) params.key = "key"
return params
}
函数扁平化
compose 函数
pipe 函数
如 React 的 HOC
ts
// 没有pipe,function hell...
withRouter(
withTitle("Awesome title")(translate("translations")(connect(mapStateToProps, mapDispatchToProps)(Container)))
)
// 使用pipe
pipe(
connect(mapStateToProps, mapDispatchToProps),
translate("translations"),
withTitle("Awesome title"),
withRouter
)(Container)
// 使用pipe组成你需要的pattern
const withGeneralContainerProps = pipe(
connect(mapStateToProps, mapDispatchToProps),
translate("translations"),
withTitle("Awesome title"),
withRouter
)
withGeneralContainerProps(Container)
高阶函数
memozition(缓存函数)
缓存函数是指将上次的计算结果缓存起来,当下次调用时,如果遇到相同的参数,就直接返回缓存中的数据
ts
let add = (a, b) => a + b
// 假设memoize函数可以实现缓存
let calculate = memoize(add)
calculate(10, 20) // 30
calculate(10, 20) // 相同的参数,第二次调用是,从缓存中取出数据,而并非重新计算一次