100字范文,内容丰富有趣,生活中的好帮手!
100字范文 > javascript实用库_编写实用JavaScript的实用指南

javascript实用库_编写实用JavaScript的实用指南

时间:2022-06-30 15:08:06

相关推荐

javascript实用库_编写实用JavaScript的实用指南

javascript实用库

by Nadeesha Cabral

通过Nadeesha Cabral

编写实用JavaScript的实用指南 (A practical guide to writing more functional JavaScript)

Functional programming is great. With the introduction of React, more and more JavaScript front-end code is being written with FP principles in mind. But how do we start using the FP mindset in everyday code we write? I’ll attempt to use an everyday code block and refactor it step by step.

函数式编程很棒。 随着React的引入,越来越多JavaScript前端代码是根据FP原理编写的。 但是,如何在编写的日常代码中开始使用FP思维方式? 我将尝试使用日常代码块并逐步对其进行重构。

Our problem:A user who comes to our/loginpage will optionally have aredirect_toquery parameter. Like/login?redirect_to=%2Fmy-page. Note that%2Fmy-pageis actually/my-pagewhen it’s encoded as the part of the URL. We need to extract this query string, and store it in local storage, so that once the login is done, user can be redirected to themy-page.

我们的问题:进入/login页面的用户可以选择使用redirect_to查询参数。 像/login?redirect_to=%2Fmy-page。 请注意,%2Fmy-page编码为URL的一部分时,实际上是/my-page。 我们需要提取此查询字符串,并将其存储在本地存储中,以便完成登录后,可以将用户重定向到my-page

步骤0:当务之急 (Step 0: The imperative approach)

If we had to express the solution in the simplest form of issuing a list of commands, how would we write it? We will need to

如果我们必须以发布命令列表的最简单形式来表达解决方案,那么我们将如何编写它呢? 我们将需要

Parse the query string.解析查询字符串。

Get theredirect_tovalue.

获取redirect_to值。

Decode that value.解码该值。 Store the decoded value in localStorage.将解码后的值存储在localStorage中。

And we have to put try catch blocks around “unsafe” functions as well. With all of that, our code block will look like:

而且我们还必须围绕“不安全”功能放置尝试捕获块。 有了这些,我们的代码块将看起来像:

步骤1:将每个步骤编写为函数 (Step 1: Writing every step as a function)

For a moment, let’s forget the try catch blocks and try expressing everything as a function here.

暂时,让我们忘记try catch块,并尝试在此处将所有内容表示为一个函数。

When we start expressing all of our “outcomes” as results of functions, we see what we can refactor out of our main function body. When that happens, our function becomes much easier to grok, and much easier to test.

当我们开始将所有“结果”表达为功能的结果时,我们看到可以从我们的主要功能主体中进行重构。 发生这种情况时,我们的功能将变得更容易使用,也更易于测试。

Earlier, we would have tested the main function as a whole. But now, we have 4 smaller functions, and some of them are just proxying other functions, so the footprint that needs to be tested is much smaller.

之前,我们将测试整个主要功能。 但是现在,我们有4个较小的功能,其中一些只是代理其他功能,因此需要测试的占地面积要小得多。

Let’s identify these proxying functions, and remove the proxy, so we have a little bit less code.

让我们识别这些代理功能,并删除代理,这样我们的代码就会少一点。

步骤2:尝试编写功能 (Step 2: An attempt at composing functions)

Alright. Now, it seems like thepersistRedirectToParamsfunction is a “composition” of 4 other functions. Let’s see whether we can write this function as a composition, thereby eliminating the interim results we store asconsts.

好的。 现在,似乎persistRedirectToParams函数是其他4个函数的“组合”。 让我们看看是否可以将此函数编写为一个组合,从而消除我们存储为const的中期结果。

This is good. But I feel for the person who reads this nested function call. If there was a way to untangle this mess, that’d be awesome.

很好 但是我对阅读此嵌套函数调用的人有感觉。 如果有办法解开这个烂摊子,那就太好了。

步骤3:更具可读性的构图 (Step 3: A more readable composition)

If you’ve done some redux or recompose, you’d have come acrosscompose. Compose is a utility function which accepts multiple functions, and returns one function that calls the underlying functions one by one. There are other excellent sources to learn about composition, so I won’t go into detail about that here.

如果您做了一些还原或重组,就会碰到compose。 Compose是一种实用程序函数,它接受多个函数,并返回一个函数,该函数一个接一个地调用基础函数。 还有其他一些很好的资料可以学习构图,因此在这里我将不做详细介绍。

With compose, our code will look like:

使用compose,我们的代码将如下所示:

One thing with compose is that it reduces functions right-to-left. So, the first function that gets invoked in thecomposechain is the last function.

compose的一件事是它从右到左减少了功能。 因此,在compose链中被调用的第一个函数是最后一个函数。

This is not a problem if you’re a mathematician, and are familiar with the concept, so you naturally read this right-to-left. But for the rest of us familiar with imperative code, we would like to read this left-to-right.

如果您是数学家并且熟悉该概念,那么这不是问题,因此您自然而然地从右到左阅读。 但是对于熟悉命令式代码的其他人,我们想从左至右阅读。

步骤4:管道和展平 (Step 4: Piping and flattening)

Luckily, there’spipe.pipedoes the same thing thatcomposedoes, but in reverse. So, the first function in the chain is the first function processing the result.

幸运的是,那里有pipepipe执行与compose相同的操作,但是相反。 因此,链中的第一个功能是处理结果的第一个功能。

Also, it seems as if ourpersistRedirectToParamsfunction has become a wrapper for another function that we callop. In other words, all it does is executeop. We can get rid of the wrapper and “flatten” our function.

同样,似乎我们的persistRedirectToParams函数已成为另一个称为op函数的包装。 换句话说,它所做的就是执行op。 我们可以摆脱包装器并“展平”我们的功能。

Almost there. Remember, that we conveniently left ourtry-catchblock behind to get this to the current state? Well, we need some way to introduce it back.qs.parseis unsafe as well asstoreRedirectToQuery. One option is to make them wrapper functions and put them intry-catchblocks. The other, functional way is to expresstry-catchas a function.

差不多了。 还记得吗,我们方便地将try-catch块留在了后面,以使其处于当前状态? 好吧,我们需要一些方法来介绍它。qs.parse是不安全以及storeRedirectToQuery。 一种选择是使它们具有包装器功能,并将其放入try-catch块中。 另一种功能性方法是将try-catch表示为一个功能。

步骤5:异常处理功能 (Step 5: Exception handling as a function)

There are some utilities which do this, but let’s try writing something ourselves.

有一些实用程序可以做到这一点,但让我们尝试自己编写一些东西。

Our function here expects anoptsobject which will containtryerandcatcherfunctions. It will return a function which, when invoked with arguments, call thetryerwith the said arguments and upon failure, call thecatcher. Now, when we have unsafe operations, we can put them in thetryersection and if they fail, rescue and give a safe result from the catcher section (and even log the error).

我们的函数在这里需要一个opts对象,其中将包含tryercatcher函数。 它将返回一个函数,当使用参数调用该tryer,将使用所述参数调用该tryer,并在失败时调用该catcher。 现在,当我们进行不安全的操作时,我们可以将它们放在tryer部分中,如果它们失败,请从catcher部分进行救援并给出安全的结果(甚至记录错误)。

步骤6:将所有内容放在一起 (Step 6: Putting everything together)

So, with that in mind, our final code looks like:

因此,考虑到这一点,我们的最终代码如下所示:

This is more or less what we want. But to make sure the readability and testability of our code improves, we can factor out the “safe” functions as well.

这或多或少是我们想要的。 但是,要确保提高代码的可读性和可测试性,我们还可以考虑“安全”功能。

Now, what we’ve got is an implementation of a much larger function, consisting of 4 individual functions that are highly cohesive, loosely coupled, can be tested independently, can be re-used independently, account for exception scenarios, and are highly declarative. (And IMO, they’re a tad bit nicer to read.)

现在,我们得到的是一个更大功能的实现,该功能由4个高度凝聚,松散耦合,可以独立测试,可以独立重用,说明异常情况且具有高度声明性的单个功能组成。 (而且IMO,它们的阅读性更好一点。)

There’s some FP syntactic sugar that makes this even nicer, but that’s for another day.

有一些FP语法糖使它变得更好,但这是另一天的事情。

翻译自: /news/a-practical-guide-to-writing-more-functional-javascript-db49409f71/

javascript实用库

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。