Functional programming’s been quite the eye-opening journey for me. This post, and posts like it, are an attempt to share my insights and perspectives as I trek new functional programming lands.
对我而言,函数式编程是一个令人大开眼界的旅程。 这篇文章以及类似的文章是我在尝试新的函数式编程领域时试图分享我的见解和观点的尝试。
Ramda’s been my go-to FP library because of how much easier it makes functional programming in JavaScript. I highly recommend it.
Ramda成为了我的首选 FP库,因为它使JavaScript中的函数式编程变得更加容易。 我强烈推荐它。
管 (Pipe)
The concept of pipe
is simple — it combines n
functions. It’s a pipe flowing left-to-right, calling each function with the output of the last one.
pipe
的概念很简单-它结合了n
功能。 这是一条从左到右流动的管道,使用最后一个输出调用每个函数。
Let’s write a function that returns someone’s name
.
让我们编写一个返回某人name
的函数。
getName = (person) => person.name;
getName({ name: 'Buckethead' });
// 'Buckethead'
Let’s write a function that uppercases strings.
让我们写一个大写字符串的函数。
uppercase = (string) => string.toUpperCase();
uppercase('Buckethead');
// 'BUCKETHEAD'
So if we wanted to get and capitalize person
's name, we could do this:
因此,如果我们想获得和利用person
的名字,我们可以这样做:
name = getName({ name: 'Buckethead' });
uppercase(name);
// 'BUCKETHEAD'
That’s fine but let’s eliminate that intermediate variable name
.
很好,但是让我们消除该中间变量name
。
uppercase(getName({ name: 'Buckethead' }));
Better, but I’m not fond of that nesting. It can get too crowded. What if we want to add a function that gets the first 6 characters of a string?
更好,但是我不喜欢这种嵌套。 太拥挤了。 如果我们想添加一个获取字符串的前6个字符的函数怎么办?