- Mastering Immutable.js
- Adam Boduch
- 206字
- 2021-07-08 10:30:12
Replacing collections with new instances
The simplest way to empty a collection is to replace it with a new instance, as shown here:
const empty = (collection) => {
if (collection instanceof List) {
return List();
}
if (collection instanceof Map) {
return Map();
}
return null;
};
const myList = List.of(1, 2);
const myMap = Map.of('one', 1, 'two', 2);
const myEmptyList = empty(myList);
const myEmptyMap = empty(myMap);
console.log('myList', myList.toJS());
// -> myList [ 1, 2 ]
console.log('myEmptyList', myEmptyList.toJS());
// -> myEmptyList []
console.log('myMap', myMap.toJS());
// -> myMap { one: 1, two: 2 }
console.log('myEmptyMap', myEmptyMap.toJS());
// -> myEmptyMap {}
We've created a little helper function called empty(). The idea is that it accepts either a list or map as its argument. Depending on the type of collection, a new instance is returned. Then, we can assign this new value to myEmptyList. Remember, as long as myList is referenced, it will never be garbage-collected. If you don't want this to happen, you could store the collection in a variable instead of in a constant. Then, empty() can simply replace the old collection:
var myList = List.of(1, 2);
myList = empty(myList);
Now, the garbage collector can pick up the first collection with the values 1 and 2.
推薦閱讀
- HTML5+CSS3+JavaScript從入門到精通:上冊(微課精編版·第2版)
- .NET之美:.NET關鍵技術深入解析
- ExtGWT Rich Internet Application Cookbook
- Java范例大全
- Python GUI Programming Cookbook
- Unity 5 for Android Essentials
- Linux C編程:一站式學習
- Python機器學習算法: 原理、實現與案例
- Visual C#.NET Web應用程序設計
- Clojure for Machine Learning
- 分布式數據庫原理、架構與實踐
- 寫給大家看的Midjourney設計書
- 金融商業數據分析:基于Python和SAS
- 基于JavaScript的WebGIS開發
- Learning Swift