- Mastering Immutable.js
- Adam Boduch
- 242字
- 2021-07-08 10:30:08
Passing Immutable.js collections
Another scenario for passing data to Immutable.js constructors is for passing other Immutable.js collections. For example, let's say that you have a map instance, just like the one that we created in the preceding section. You can then do the following:
const firstMap = Map({ a: 1, b: 2, c: 3 });
console.log('myMap', myMap.get('a'));
// -> myMap 1
As expected, you get a new map instance in the firstMap constant. Now let's use this first instance as the input for creating another map:
const myMap = Map(firstMap);
console.log('firstMap === myMap', firstMap === myMap);
// -> firstMap === myMap true
Wait, if Immutable.js maps are immutable, how can firstMap be the same reference as myMap? This is a trick that Immutable.js uses to avoid having to create another instance of the exact same collection. By doing this, you're not actually violating any kind of immutability constraints. The collection that is passed to Map() can't change, so creating a copy of it is wasteful.
This can be useful if you're creating a function that accepts a collection as an argument:
const myFunc = map => Map(map).toJS();
console.log('myFunc(object)', myFunc({ a: 1, b: 2, c: 3 }));
// -> myFunc(object) { a: 1, b: 2, c: 3 }
console.log('myFunc(map)', myFunc(myMap));
// -> myFunc(map) { a: 1, b: 2, c: 3 }
- Go Web編程
- Mastering Entity Framework Core 2.0
- 測試驅動開發:入門、實戰與進階
- 薛定宇教授大講堂(卷Ⅳ):MATLAB最優化計算
- JavaScript動態網頁開發詳解
- Unity 2D Game Development Cookbook
- MySQL入門很輕松(微課超值版)
- Developing SSRS Reports for Dynamics AX
- 從零開始:UI圖標設計與制作(第3版)
- Scala編程(第5版)
- Maker基地嘉年華:玩轉樂動魔盒學Scratch
- UML2面向對象分析與設計(第2版)
- 算法圖解
- Mastering Apache Camel
- ASP.NET開發寶典