官术网_书友最值得收藏!

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.

主站蜘蛛池模板: 临洮县| 保康县| 晋城| 察哈| 大方县| 米易县| 高青县| 朝阳市| 延边| 彝良县| 当阳市| 葫芦岛市| 玉门市| 万载县| 疏附县| 通山县| 山西省| 蓝田县| 松阳县| 蓬安县| 乌拉特后旗| 嫩江县| 西安市| 大姚县| 闸北区| 封开县| 广南县| 荃湾区| 马公市| 丹寨县| 垣曲县| 磐安县| 长乐市| 浮梁县| 莱阳市| 渑池县| 五大连池市| 金湖县| 乌兰浩特市| 昔阳县| 桃源县|