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 /login
page will optionally have a redirect_to
query parameter. Like /login?redirect_to=%2Fmy-page
. Note that %2Fmy-page
is actually /my-page
when 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 the my-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 the
redirect_to
value.獲取
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 the persistRedirectToParams
function 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 as const
s.
好的。 現在,似乎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 across compose
. 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 the compose
chain 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’s pipe
. pipe
does the same thing that compose
does, but in reverse. So, the first function in the chain is the first function processing the result.
幸運的是,那里有pipe
。 pipe
執行與compose
相同的操作,但是相反。 因此,鏈中的第一個功能是處理結果的第一個功能。
Also, it seems as if our persistRedirectToParams
function has become a wrapper for another function that we call op
. In other words, all it does is execute op
. We can get rid of the wrapper and “flatten” our function.
同樣,似乎我們的persistRedirectToParams
函數已成為另一個稱為op
函數的包裝。 換句話說,它所做的就是執行op
。 我們可以擺脫包裝器并“展平”我們的功能。
Almost there. Remember, that we conveniently left our try-catch
block behind to get this to the current state? Well, we need some way to introduce it back. qs.parse
is unsafe as well as storeRedirectToQuery
. One option is to make them wrapper functions and put them in try-catch
blocks. The other, functional way is to express try-catch
as 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 an opts
object which will contain tryer
and catcher
functions. It will return a function which, when invoked with arguments, call the tryer
with the said arguments and upon failure, call the catcher
. Now, when we have unsafe operations, we can put them in the tryer
section and if they fail, rescue and give a safe result from the catcher section (and even log the error).
我們的函數在這里需要一個opts
對象,其中將包含tryer
和catcher
函數。 它將返回一個函數,當使用參數調用該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語法糖使它變得更好,但這是另一天的事情。
翻譯自: https://www.freecodecamp.org/news/a-practical-guide-to-writing-more-functional-javascript-db49409f71/
javascript實用庫