函数式编程

看到这里,我们已经了解了关于纯净性,状态,不可变性,声明式编程和高阶函数的内容。这些都是理解函数式编程范式至关重要的概念。

实践:用JavaScript来函数式编程

函数式编程由以下概念构成:

  • 主要功能由没有副作用的纯函数实现。
  • 数据是不可变的。
  • 功能函数是无状态的。
  • 外部容器(命令式)代码管理副作用并执行(声明式)核心代码。*

*如果我们尝试写一个由纯函数(无副作用)组成的JavaScript web应用,它不能与环境产生交互,因此将用途不大。

让我们看个例子,假设我们有一个text的副本,并且我们想得到它的文字长度,我们还想招到长度大于5个字符的关键字。如果用函数式编程,我们的目标代码可能看上去像这样:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
const fpCopy = `Functional programming is powerful and enjoyable to write. It's very cool!`;

// 移除标点符号
const stripPunctuation = (str) =>
str.replace(/[.,\/#!$%\^&\*;:{}=\-_`~()]/g, '');

// 根据空格分隔生成数组
const getArr = (str) =>
str.split(' ');

// 对传递的数组中的项进行计数
const getWordCount = (arr) =>
arr.length;

// 在传递的数组中查找长度超过5个字符的元素
// 小写
const getKeywords = (arr) =>
arr
.filter(item => item.length > 5)
.map(item => item.toLowerCase());

// 处理copy以准备字符串、创建数组、计数单词和获取关键字
function processCopy(str, prepFn, arrFn, countFn, kwFn) {
const copyArray = arrFn(prepFn(str));

console.log(`Word count: ${countFn(copyArray)}`);
console.log(`Keywords: ${kwFn(copyArray)}`);
}

processCopy(fpCopy, stripPunctuation, getArr, getWordCount, getKeywords);
// 结果: Word count: 11
// 结果: Keywords: functional,programming,powerful,enjoyable

它被分解为易于理解的、具有明确目的的声明式函数。如果我们单步执行并阅读注释,其实并不需要进一步解释代码。每一个核心功能都是模块化的,并且只依赖它的输入(纯净性)。最后那个函数处理了核心功能并生成了输出集合。这个processCopy()函数,相当于一个非纯容器,用以执行核心功能并管理副作用。我们使用高阶函数,接受其他函数作为参数,来维护函数式风格。

函数式编程的优势

不可变数据和无状态性意味着程序存在的状态不会被修改,相反的,会返回新的值。纯函数被用做核心功能,为了实现功能并处理必要的副作用,非纯函数应该命令式的调用纯函数。

想学习更多函数式编程相关,可参考下列资源:
Introduction to Immutable.js and Functional Programming Concepts
Functional Programming For The Rest of Us
Functional Programming with JavaScript
Don’t be Scared of Functional Programming
So You Want to be a Functional Programmer
lodash - Functional Programming Guide
What is the difference between functional and imperative programming languages?
Eloquent JavaScript, 1st Edition - Functional Programming
Functional Programming by Example
Functional Programming in JavaScript - Video Series
Introduction to Functional JavaScript
How to perform side effects in pure functional programming
Preventing Side Effects in JavaScript


阅读原文:https://auth0.com/blog/glossary-of-modern-javascript-concepts/