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 /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

如果我們必須以發布命令列表的最簡單形式來表達解決方案,那么我們將如何編寫它呢? 我們將需要

  1. Parse the query string.

    解析查詢字符串。
  2. Get the redirect_to value.

    獲取redirect_to值。

  3. Decode that value.

    解碼該值。
  4. 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 consts.

好的。 現在,似乎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.

幸運的是,那里有pipepipe執行與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對象,其中將包含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語法糖使它變得更好,但這是另一天的事情。

翻譯自: https://www.freecodecamp.org/news/a-practical-guide-to-writing-more-functional-javascript-db49409f71/

javascript實用庫

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/392538.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/392538.shtml
英文地址,請注明出處:http://en.pswp.cn/news/392538.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

數據庫數據過長避免_為什么要避免使用商業數據科學平臺

數據庫數據過長避免讓我們從一個類比開始 (Lets start with an analogy) Stick with me, I promise it’s relevant.堅持下去,我保證這很重要。 If your selling vegetables in a grocery store your business value lies in your loyal customers and your positi…

mysql case快捷方法_MySQL case when使用方法實例解析

首先我們創建數據庫表: CREATE TABLE t_demo (id int(32) NOT NULL,name varchar(255) DEFAULT NULL,age int(2) DEFAULT NULL,num int(3) DEFAULT NULL,PRIMARY KEY (id)) ENGINEInnoDB DEFAULT CHARSETutf8;插入數據:INSERT INTO t_demo VALUES (1, 張…

【~~~】POJ-1006

很簡單的一道題目,但是引出了很多知識點。 這是一道中國剩余問題,先貼一下1006的代碼。 #include "stdio.h" #define MAX 21252 int main() { int p , e , i , d , n 1 , days 0; while(1) { scanf("%d %d %d %d",&p,&e,&…

Java快速掃盲指南

文章轉自:https://segmentfault.com/a/1190000004817465#articleHeader22 JDK,JRE和 JVM 的區別 JVM:java 虛擬機,負責將編譯產生的字節碼轉換為特定機器代碼,實現一次編譯多處執行; JRE:java運…

xcode擴展_如何將Xcode插件轉換為Xcode擴展名

xcode擴展by Khoa Pham通過Khoa Pham 如何將Xcode插件轉換為Xcode擴展名 (How to convert your Xcode plugins to Xcode extensions) Xcode is an indispensable IDE for iOS and macOS developers. From the early days, the ability to build and install custom plugins ha…

leetcode 861. 翻轉矩陣后的得分(貪心算法)

有一個二維矩陣 A 其中每個元素的值為 0 或 1 。 移動是指選擇任一行或列,并轉換該行或列中的每一個值:將所有 0 都更改為 1,將所有 1 都更改為 0。 在做出任意次數的移動后,將該矩陣的每一行都按照二進制數來解釋,矩…

數據分析團隊的價值_您的數據科學團隊的價值

數據分析團隊的價值This is the first article in a 2-part series!!這是分兩部分的系列文章中的第一篇! 組織數據科學 (Organisational Data Science) Few would argue against the importance of data in today’s highly competitive corporate world. The tech…

mysql 保留5位小數_小猿圈分享-MySQL保留幾位小數的4種方法

今天小猿圈給大家分享的是MySQL使用中4種保留小數的方法,希望可以幫助到大家,讓大家的工作更加方便。1 round(x,d)用于數據x的四舍五入, round(x) ,其實就是round(x,0),也就是默認d為0;這里有個值得注意的地方是,d可以是負數&…

leetcode 842. 將數組拆分成斐波那契序列(回溯算法)

給定一個數字字符串 S&#xff0c;比如 S “123456579”&#xff0c;我們可以將它分成斐波那契式的序列 [123, 456, 579]。 形式上&#xff0c;斐波那契式序列是一個非負整數列表 F&#xff0c;且滿足&#xff1a; 0 < F[i] < 2^31 - 1&#xff0c;&#xff08;也就是…

博主簡介

面向各層次&#xff08;從中學到博士&#xff09;提供GIS和Python GIS案例實驗實習培訓&#xff0c;以解決問題為導向&#xff0c;以項目實戰為主線&#xff0c;以科學研究為思維&#xff0c;不講概念&#xff0c;不局限理論&#xff0c;簡單照做&#xff0c;即學即會。 研究背…

自定義Toast 很簡單就可以達到一些對話框的效果 使用起來很方便

自定義一個layout布局 通過toast.setView 設置布局彈出一些警示框 等一些不會改變的提示框 很方便public class CustomToast {public static void showUSBToast(Context context) {//加載Toast布局 View toastRoot LayoutInflater.from(context).inflate(R.layout.toas…

微信小程序阻止冒泡點擊_微信小程序bindtap事件與冒泡阻止詳解

bindtap就是點擊事件在.wxml文件綁定:cilck here在一個組件的屬性上添加bindtap并賦予一個值(一個函數名)當點擊該組件時, 會觸發相應的函數執行在后臺.js文件中定義tapMessage函數://index.jsPage({data: {mo: Hello World!!,userid : 1234,},// 定義函數tapMessage: function…

同情機器人_同情心如何幫助您建立更好的工作文化

同情機器人Empathy is one of those things that can help in any part of life whether it’s your family, friends, that special person and even also at work. Understanding what empathy is and how it effects people took me long time. I struggle with human inter…

數據庫課程設計結論_結論

數據庫課程設計結論When writing about learning or breaking into data science, I always advise building projects.在撰寫有關學習或涉足數據科學的文章時&#xff0c;我總是建議構建項目。 It is the best way to learn as well as showcase your skills.這是學習和展示技…

mongo基本使用方法

mongo與關系型數據庫的概念對比&#xff0c;區分大小寫&#xff0c;_id為主鍵。 1.數據庫操作 >show dbs #查看所有數據庫 >use dbname #創建和切換數據庫&#xff08;如果dbname存在則切換到該數據庫&#xff0c;不存在則創建并切換到該數據庫&#xff1b;新創建的…

leetcode 62. 不同路徑(dp)

一個機器人位于一個 m x n 網格的左上角 &#xff08;起始點在下圖中標記為“Start” &#xff09;。 機器人每次只能向下或者向右移動一步。機器人試圖達到網格的右下角&#xff08;在下圖中標記為“Finish”&#xff09;。 問總共有多少條不同的路徑&#xff1f; 例如&…

第一名數據科學工作冠狀病毒醫生

背景 (Background) 3 years ago, I had just finished medical school and started working full-time as a doctor in the UK’s National Health Service (NHS). Now, I work full-time as a data scientist at dunnhumby, writing code for “Big Data” analytics with Pyt…

mysql時間區間效率_對于sql中使用to_timestamp判斷時間區間和不使用的效率對比及結論...

關于日期函數TO_TIMESTAMP拓展&#xff1a;date類型是Oracle常用的日期型變量&#xff0c;時間間隔是秒。兩個日期型相減得到是兩個時間的間隔&#xff0c;注意單位是“天”。timestamp是DATE類型的擴展&#xff0c;可以精確到小數秒(fractional_seconds_precision)&#xff0c…

ajax 賦值return

ajax 獲得結果后賦值無法成功&#xff0c; function grades(num){ var name"";   $.ajax({    type:"get",     url:"",     async:true,     success:function(result){     var grades result.grades;     …

JavaScript(ES6)傳播算子和rest參數簡介

by Joanna Gaudyn喬安娜高登(Joanna Gaudyn) JavaScript(ES6)傳播算子和rest參數簡介 (An intro to the spread operator and rest parameter in JavaScript (ES6)) 擴展運算符和rest參數都被寫為三個連續的點(…)。 他們還有其他共同點嗎&#xff1f; (Both the spread opera…