admin管理员组

文章数量:1582347

Functional Programming, a buzzword got every enthusiastic developer thinking. Functional Programming is programming paradigm a.k.a a style of thinking and building the structure of the software based on some rules that includes:

“函数式编程”这个流行语引起了所有开发人员的热情思考。 功能编程是一种编程范式,又是一种思维方式,它基于一些规则来构建软件的结构,这些规则包括:

  • Pure functions

    纯功能
  • Function composition

    功能组成
  • Avoid shared state

    避免共享状态
  • Avoid mutating state

    避免改变状态
  • Avoid side effects

    避免副作用

Today I will talk about avoiding mutation part of the rule set. Avoiding mutation means you can’t change a object once it created. Seems fun and interesting ? Yes!! However, while working in real life project with immutability in consideration life will be little hard at the beginning. So in this post lets try to grasp the logic through some examples.

今天,我将讨论避免规则集中的突变部分。 避免突变意味着一旦创建对象便无法更改。 看起来有趣又有趣? 是!! 但是,在现实生活中工作时,考虑到不变性,一开始生活会很困难。 因此,在本文中,我们将尝试通过一些示例来掌握逻辑。

Immutable.js (Immutable.js)

We will use immutable.js for our purpose. You can see the documentation here. For installation:

我们将出于目的使用immutable.js。 您可以在此处查看文档。 安装:

npm install immutable

We will use List today so lets use destructuring concept:

我们今天将使用List ,因此我们使用分解概念:

import { List } from 'immutable';

You can also use the good old syntax for importing:

您也可以使用良好的旧语法进行导入:

const { List } = require('immutable');

清单 (List)

First thing first, what is list ? Array [] is List List([]) . Lets Say we will create a List of 1,2,3,4,5 we can use two approaches:

首先,列表是什么? 数组[]是列表List([]) 。 假设我们将创建1,2,3,4,5的列表,我们可以使用两种方法:

If you console.log()this you will get a crazy object like:

如果您使用console.log()您将得到一个疯狂的对象,例如:

We will use toJS() to convert this to equivalent native JavaScript Array.

我们将使用toJS()将其转换为等效的本机JavaScript数组。

Now lets say we already have an array and we want to convert the array into a immutable list. Like toJS() we will use fromJS() to do the opposite.

现在假设我们已经有了一个数组,并且想要将该数组转换为不可变列表。 像toJS()一样,我们将使用fromJS()做相反的事情。

Here we use isImmutable() to check if the list is immutable or not. It returns true !! So fromJS() can turn our mutable array to an immutable list.

在这里,我们使用isImmutable()来检查列表是否不可变。 它返回true! 因此fromJS()可以将可变数组变成不可变的列表。

Now Lets start with solving a simple problem:

现在让我们开始解决一个简单的问题:

We have an empty list and we will have to insert 1 to 10.

我们有一个空列表,我们将必须插入1到10。

However, every modification in the list will create a new List

但是,列表中的每个修改都会创建一个新的列表

Now you must be thinking wait if every modification will create a new list, how we supposed to solve this ? Cause every insert into the list will create a new list. Recursion comes and saves the day:

现在,您必须考虑是否每次修改都会创建一个新列表,我们应该如何解决呢? 因为每次插入列表都会创建一个新列表。 递归来并节省了一天:

In the above code, we can see addValue() is a recursive function. Its taking the list and limit as parameter. You might think why taking list as a parameter when we declared list globally. Here comes the pure function concept, a pure function should not depend on variable outside of the scope.

在上面的代码中,我们可以看到addValue()是一个递归函数。 它以列表和限制为参数。 您可能会想为什么在全局声明list时为什么将list作为参数。 这是纯函数的概念,纯函数不应依赖范围之外的变量。

Lets try to solve the greatest problem till date -> “FizzBuzz” 😛

让我们尝试解决迄今为止最大的问题-> “ FizzBu​​zz” 😛

But we will modify the problem a bit:

但是,我们将对该问题进行一些修改:

Given a list print the numbers. But for multiples of three print “Fizz” instead of the number and for the multiples of five print “Buzz”. For numbers which are multiples of both three and five print “FizzBuzz”.

给定列表,打印数字。 但是,对于三倍打印“ Fizz”而不是数字,对于五倍打印“ Buzz”。 对于三和五的倍数的数字,请打印“ FizzBu​​zz”。

Here we used the update() method of list. We can also use set() for this use case. We also used list.get(index) to get value of an index. There is a work around we can use so that for every change new object will not be created, instead after all the changes at the end the updated object will be created. Lets solve this again but now with withMutations :

在这里,我们使用了list的update()方法。 我们也可以在此用例中使用set() 。 我们还使用list.get(index)来获取索引值。 我们可以使用一种解决方法,以便对于每次更改都不会创建新对象,而是在所有更改结束后都会创建更新的对象。 让我们再次解决此问题,但现在使用withMutations

withMutations will create a temporary list and apply a batch of mutations and at the end return the updated immutable list. However, it is highly discouraged to use withMutations because it will add some overhead and it can add up to a performance penalty. Remember, not all methods can be used with withMutations . If you need to use withMutations please go through the docs before applying.

withMutations将创建一个临时列表并应用一批突变,最后返回更新的不可变列表。 但是,强烈建议不要将其与withMutations一起使用,因为它会增加一些开销,并可能导致性能withMutations 。 请记住,并非所有方法都可以与withMutations一起使用。 如果您需要使用withMutations请在申请前withMutations文档。

We have learned how to use immutable list in a loop with recursion and also we can use withMutations if we don’t want to use recursion. Now lets implement an algorithm with immutable list -> “Insertion Sort”

我们已经学习了如何在带有递归的循环中使用不可变列表,并且如果我们不想使用递归,也可以使用withMutations 。 现在,让我们实现一个具有不变列表的算法->“ 插入排序”

Insertion sort have a nested loop. To meet up the requirements of Functional Programming I have replaced the first loop with map and for the inner loop just replaced with a recursive function. Now everything is more testable and side effect free.

插入排序有一个嵌套循环。 为了满足函数式编程的要求,我已将第一个循环替换为map,而对于内部循环则仅替换了递归函数。 现在,所有内容都可测试且无副作用。

I want to show you to some useful methods of List which might help you.

我想向您展示一些可能有用的List方法。

Basic difference between set(), insert() and push() :

set()insert()push()之间的基本区别:

Lets say we have 2D list and we want to make modification. We will have to use setIn(), deleteIn(), updateIn(). Some example:

假设我们有2D列表,我们想进行修改。 我们将不得不使用setIn()deleteIn()updateIn() 。 一些例子:

setIn([2,1],2) first go to the index 2 which is [0,3] then go to the index 1 of this list which is 3 and set it to 2. This is how we can easily modify a nested List.

setIn([2,1],2)首先转到索引[0,3] 2 [0,3] ,即[0,3]然后转到该列表的索引1,即3,并将其设置为2。这就是我们可以轻松修改嵌套的方法清单。

Lastly, if we want to make a 2D list or merge two lists we can use zip() and merge() respectively:

最后,如果我们要制作2D列表或合并两个列表,可以分别使用zip()merge()

In this part, I tried to show how we can easily use immutable List and have all the feasibility like array and also get all the benefits of immutability. In the next part I will try to show how we can use immutable Map to do all the stuff we can do with Object{}.

在这一部分中,我试图说明如何轻松使用不可变列表,并具有数组之类的所有可行性,并获得不可变性的所有好处。 在下一部分中,我将尝试展示如何使用不可变Map来完成我们可以使用Object{}完成的所有工作。

翻译自: https://medium/@md.fahim.hasnat/immutable-js-part-1-all-about-list-84286c90cb5d

本文标签: 列表js