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

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.

主站蜘蛛池模板: 巴中市| 长治市| 图木舒克市| 张北县| 汽车| 正宁县| 班戈县| 阜城县| 沁水县| 平乡县| 永靖县| 乳山市| 翼城县| 河北区| 田林县| 天门市| 台州市| 霍城县| 儋州市| 台北县| 翁源县| 教育| 怀仁县| 杨浦区| 大英县| 东乡县| 黑水县| 高碑店市| 渑池县| 普定县| 容城县| 临颍县| 龙南县| 隆昌县| 方城县| 东海县| 衡阳市| 大厂| 瓮安县| 沂水县| 灵宝市|