typescript中函数_如何使用TypeScript中的函数式编程使生活更轻松

typescript中函数

by Mateusz Sokola

由Mateusz Sokola

如何使用TypeScript中的函数式编程使生活更轻松 (How to make your life easier using functional programming in TypeScript)

Over the last two years, the JavaScript community has been talking about functional programming. Functional programming allows us to build better software without designing complex class trees. Today, I will explain how to use function composition in Typescript and Lodash.

在过去的两年中,JavaScript社区一直在谈论函数式编程。 函数式编程使我们能够构建更好的软件,而无需设计复杂的类树。 今天,我将解释如何在TypescriptLodash中使用函数组合。

The code can be found on Github.

可以在Github找到该代码。

什么是功能组成? (What is function composition?)

Function composition involves combining two or more functions to create a more complex one. Feeling confused? No worries, the following example will make it clear:

功能组合涉及将两个或多个功能组合在一起以创建更复杂的功能。 感觉困惑? 不用担心,下面的示例将清楚说明:

const f = function (a) { return a + 1 };const g = function (b) { return b * b };
const x = 2;const result = f(g(x)); // => 5

I combined two functions here — function f and function g. Function f adds 1 to the a parameter, and function g multiplies the b parameter by b. The result is 5.

我在这里结合了两个功能-功能f和功能g。 函数f将a加到a参数,函数gb参数乘以b 。 结果是5。

Let’s reverse-engineer it:

让我们对其进行反向工程:

  1. constant x equals 2

    常数x等于2

  2. constant x becomes an argument of function g

    常数x成为函数g的自变量

  3. function g returns 4

    函数g返回4

  4. function g output (4) becomes an argument of function f

    功能g输出(4) 成为函数f的参数

  5. function f returns 5

    函数f返回5

It’s not rocket science, but it doesn’t look particularly useful. Actually, it looks even more complex than keeping it within one function. That may be true, but let’s consider some realistic use cases.

这不是火箭科学,但看起来并不是特别有用。 实际上,它看起来比将其保留在一个函数中更为复杂。 可能是正确的,但让我们考虑一些实际的用例。

实际示例:货币格式 (The real-world example: money formatting)

I was building a simple job posting for developers. One of the requirements was to display salary ranges next to every offer. All salaries were stored as cents and needed to look like this:

我正在为开发人员构建一个简单的职位发布。 要求之一是在每个报价旁边显示薪水范围。 所有薪水都存储为美分,需要看起来像这样:

from: 6000000 to:   60,000.00 USD

It looks easy, but working with text is hard. Almost every developer hates it.

看起来很简单,但是处理文本却很困难。 几乎每个开发人员都讨厌它。

We all spend hours writing regular expressions and dealing with unicode. When I need to format text, I am always trying to Google the solution. After cutting off all libraries (way too much for my needs) and all the code snippets that suck, there’s not so much left.

我们所有人都花数小时编写正则表达式并处理unicode。 当我需要格式化文本时,我总是尝试使用Google解决方案。 切断所有库(满足我的需求太多)和所有令人讨厌的代码段之后,剩下的就不多了。

I decided I needed to build it on my own formatter.

我决定需要在自己的格式化程序上构建它。

我们如何建造它? (How do we build it?)

Before we start to write code, let’s dig into an idea I found:

在开始编写代码之前,让我们深入研究一下我发现的想法:

  1. Split dollars and cents.

    拆分美元和美分。
  2. Format dollars — adding thousand separators is not so easy.

    格式化美元-添加千位分隔符并非易事。
  3. Format cents — dealing with cents is easy, almost out-of-the-box.

    格式化美分-处理美分很容易,几乎是开箱即用的。
  4. Connect together dollars and cents with the separator.

    用分隔符将美元和美分连接在一起。

Now it looks clear. The last thing we need to consider is how to add thousand separators to the dollars. Let’s consider the following algorithm:

现在看起来很清楚。 我们需要考虑的最后一件事是如何在美元中添加千位分隔符。 让我们考虑以下算法:

  1. Reverse string.

    反向字符串。
  2. Split string every 3 characters to array.

    每3个字符将字符串拆分为一个数组。
  3. Join all array elements together, by adding the thousand separator between them.

    通过在它们之间添加千位分隔符,将所有数组元素连接在一起。
  4. Reverse string.

    反向字符串。

All these steps can be translated into the following pseudo code:

所有这些步骤都可以转换为以下伪代码:

1. "60000"        => "00006"2. "00006"        => ["000", "06"]3. ["000", "06"]  => "000.06"4. "000.06"       => "60.000"

And this is how this algorithm is translated into composed functions:

这就是该算法如何转换为组合函数的方式:

In the first line, you’ll notice that I used the Lodash library. Lodash contains lots of utilities that make functional programming easier. Let’s analyze the code from line 22:

在第一行中,您会注意到我使用了Lodash库。 Lodash包含许多实用程序,可简化函数式编程。 让我们分析第22行的代码:

return flow([  reverse,  splitCurry(match),  joinCurry(separator),  reverse]);

The flow function is a function composer. It pipelines the result of the reverse function to the input of splitCurry, and so on. This creates an entirely new function. Remember the thousand separation algorithm from above? That’s it!

流程功能是功能编写器。 它将反向函数的结果通过管道传递给splitCurry的输入,依此类推。 这将创建一个全新的功能。 还记得上面的千位分隔算法吗? 而已!

You can see that I postfixed split and join functions with “Curry” and invoked them. This technique is called currying.

您可以看到我用“ Curry”将后缀和连接函数后缀了并调用了它们。 这项技术称为currying。

什么是咖喱? (What is Currying?)

Currying is the process of translating a many argument function into a single argument function. The single argument function returns another function if any arguments are still needed.

咖喱化是将多个参数函数转换为单个参数函数的过程。 如果仍然需要任何参数,则单个参数函数将返回另一个函数。

Sounds tough? Consider the following example:

听起来很难? 考虑以下示例:

The split function needs two arguments — a string and separation pattern. The function needs to know how to split the text. In this case, we can’t compose this function as it needs different arguments than the others. Here’s where currying comes in.

split函数需要两个参数-字符串和分隔模式。 该功能需要知道如何分割文本。 在这种情况下,我们无法编写此函数,因为它需要与其他函数不同的参数。 这是咖喱的来源。

import { curry } from "lodash";import split from "./split";
const splitCurry = curry(split);
splitCurry("000001")(/[0-9]{1,3}/g); // => ["000", "001"]

Now the splitCurry function is consistent with the reverse function. Both of them need one argument. Unfortunately, we didn’t invoke the splitCurry function with a separation pattern yet. It’s not gonna work this way.

现在splitCurry函数与反向函数一致。 他们两个都需要一个论点。 不幸的是,我们还没有使用分离模式来调用splitCurry函数。 这样行不通。

What if we reverse the argument order in our curry?

如果我们改变咖喱中的论据顺序怎么办?

import { curryRight } from "lodash";import split from "./split";
const splitCurry = curryRight(split);
splitCurry(/[0-9]{1,3}/g)("000001"); // => ["000", "001"]

Now our code may work as we can use curries as factory functions. Let’s see the code again:

现在我们的代码可以正常工作了,因为我们可以将咖喱用作工厂函数。 让我们再次看一下代码:

return flow([  reverse,  splitCurry(match),  joinCurry(separator),  reverse]);

All these functions take a single argument (string), so we can compose them together. And then use them as a standalone function. Wait a minute…

所有这些函数都采用单个参数(字符串),因此我们可以将它们组合在一起。 然后将它们用作独立功能。 等一下…

什么是工厂功能? (What are factory functions?)

Factory functions are functions that create a new object. In our case, a function. Let’s consider our thousand separator again. In theory, we can use the same function all the time. Unfortunately, some countries separate thousands with commas, others with dots. Of course I could parametrize the separator, but I decided to use the factory function.

工厂函数是创建新对象的函数。 在我们的例子中,是一个函数。 让我们再次考虑千位分隔符。 从理论上讲,我们可以一直使用相同的功能。 不幸的是,一些国家用逗号分隔成千上万,另一些国家则用点分隔。 当然,我可以参数化分隔符,但是我决定使用工厂功能。

const formatUS = thousandSeparator(',');const formatEU = thousandSeparator('.');
formatUS(10000); // 10,000formatEU(10000); // 10.000

摘要 (Summary)

Last year I spent time refreshing my knowledge from previous studies so I could apply it in my daily business. In this article, I didn’t dig into monad law or monoids — I didn’t want to make it confusing. The subject is broad and deeply rooted in computer science. I wanted to give you an idea about how to approach functional thinking while describing all terms as briefly as possible.

去年,我花时间刷新了以前的研究知识,以便将其应用于我的日常业务。 在本文中,我没有深入研究monad法则或monoids-我不想使它令人困惑。 该主题广泛而深入地扎根于计算机科学。 我想给您一个关于如何进行功能性思考的想法,同时尽可能简短地描述所有术语。

I decided to keep all the code on my Github, so the article is easier to read.

我决定将所有代码保留在我的Github上 ,因此文章更易于阅读。

If you have any problems or suggestions, please write a comment.

如果您有任何问题或建议,请写评论。

-

PS. I started a YouTube channel on programming. Please check it out and subscribe:)

PS。 我开了一个YouTube编程频道 。 请签出并订阅:)

翻译自: https://www.freecodecamp.org/news/how-to-make-your-life-easier-using-functional-programming-in-typescript-a2def76c468b/

typescript中函数

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值