- 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 }
- Docker and Kubernetes for Java Developers
- 深入淺出Prometheus:原理、應用、源碼與拓展詳解
- C語言程序設計教程(第2版)
- 匯編語言程序設計(第2版)
- 零基礎學Python網絡爬蟲案例實戰全流程詳解(入門與提高篇)
- Creating Stunning Dashboards with QlikView
- Unity 2017 Mobile Game Development
- ASP.NET開發與應用教程
- Statistical Application Development with R and Python(Second Edition)
- Learning Node.js for .NET Developers
- Visual Studio Code 權威指南
- JavaScript Unit Testing
- Learning Google Apps Script
- Learning Rust
- ServiceDesk Plus 8.x Essentials