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实用库

javascript实用库_编写实用JavaScript的实用指南相关推荐

  1. 数据库可视化库_漂亮的javascript数据可视化库

    数据库可视化库 If you're building a web app using JavaScript, it is inevitable that at some point you'll ne ...

  2. javascript创建类_如何使用JavaScript创建吹气效果

    javascript创建类 Have you ever wondered how you can create a realistic air blowing effect with JavaScri ...

  3. javascript 全栈_什么是JavaScript? 全栈编程语言

    javascript 全栈 JavaScript是一种流行的解释性脚本语言,在2019年初成为开发人员最常学习的语言 . JavaScript是一种开放标准,不受任何单一供应商的控制,具有多种实现方式 ...

  4. javascript最新版本_什么是JavaScript!

    JavaScrip的简称"js" 是一种具有函数优先的轻量级,解释型或即时编译型的高级编程语言.虽然它是作为开发前端页面的脚本语言而出名的,但是它也被用到了很多非浏览器环境中,Ja ...

  5. python数据展示库_收藏!盘点很实用的数据科学Python库

    数据科学是一门研究数据并从中挖掘信息的学科.它不要求自创或学习新的算法,只需要知道怎么样研究数据并解决问题.这一过程的关键点之一就在于使用合适的库.本文概述了数据科学中常用的.并且有一定重要性的库.在 ...

  6. javascript 高级程序设计_重读《JavaScript高级程序设计》

    最近自己在休假,打算闭门几天将<JavaScript高级程序设计>(第3版)这本良心教材再回顾一遍.目前自己进入前端领域两年多,现在重读并记录下这本教材的"硬"知识点 ...

  7. javascript中索引_如何在JavaScript中找到数字在数组中所属的索引

    javascript中索引 Sorting is a very important concept when writing algorithms. There are all kinds of so ...

  8. javascript的参数_如何使用JavaScript制作参数家具

    javascript的参数 by O-LAP 由O-LAP 如何使用JavaScript制作参数家具 (How you can make parametric furniture with JavaS ...

  9. 实用插件_精选 10 个非常实用的 VS Code 插件

    来源:Daan 原文:https://medium.com/better-programming/10-extremely-helpful-visual-studio-code-plugins-for ...

最新文章

  1. ORB_SLAM2 定位模式
  2. CV领域最经典的Paper是什么来头?
  3. Fitnesse测试系列--如何设置SetUp文件
  4. html5知识总结,HTML5初级知识总结
  5. 发现IE7 Quick Tabs内容同步有bug
  6. 2015/Province_C_C++_C/6/奇妙的数字
  7. 高级数据结构与算法 | 深度遍历搜索(DFS)与广度遍历搜索(BFS)
  8. SAP C4C Adapt menu debugging
  9. STM32串口的使用(原理、结构体、库函数、串口发送字符(串)、重定向printf串口发送、串口中断接收控制灯)
  10. jsp文件通常用common_springboot还能这样用redis
  11. mongoose 查询 find 指定字段
  12. 世上的人大都只会“飞鸽传书下载”,没人开发
  13. linux 不重启加载内核,解决linux内核升级后不能重启系统的故障
  14. 网络TCp数据的传输设计(黏包处理)
  15. 关于MYSQL的 insert 的一些方法说明
  16. MySQL8.0数据库配置注意事项
  17. 在线教育工具—白板系统的迭代1——bug监控排查
  18. Collection与Arrays
  19. 坚持学习、只是尽力维持不退步吧了
  20. 图书信息管理系统 数据结构 C语言版

热门文章

  1. 网易严选Java开发三面面经:南京黑马java培训怎么样
  2. JAVA List集合转Page(分页对象)
  3. 转载 JDK + Android-SDK + Python + MonkeyRunner 的安装
  4. hadoop环境搭建笔记
  5. NGUI之输入文本框的使用
  6. Sphinx编译docs文档
  7. NSRange的用法【转】
  8. DotNetBar office2007效果
  9. 阿里云天池 Python训练营Task4: Python数据分析:从0完成一个数据分析实战 学习笔记
  10. 混合模型和EM---混合高斯