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

Using the clear() method

You don't actually have to create a utility function to empty collections by replacing them with new instances. The clear() method does the same thing:

const myList = List.of(1, 2);
const myMap = Map.of('one', 1, 'two', 2);

// Create new instances by emptying the
// existing instances.
const myEmptyList = myList.clear();
const myEmptyMap = myMap.clear();

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 {}

The benefit with the clear() method is that you don't have to invent a utility function that returns new collection instances based on type. Another advantage is that the clear() method will first check to see if the collection is already empty and, if so, it will return the current collection.

Immutable.js does something neat when it creates new collections. The first time an empty collection is created, let's say a list, that same list instance is reused whenever an empty list is needed. If you create an empty list ( List()), or clear a list ( myList.clear()), the same instance is reused every time. This is only possible because collections are immutable.
主站蜘蛛池模板: 宁陕县| 泽州县| 会同县| 隆化县| 阿克| 年辖:市辖区| 金乡县| 苏州市| 延寿县| 师宗县| 囊谦县| 颍上县| 翼城县| 鄢陵县| 神农架林区| 灵川县| 兴城市| 南木林县| 庐江县| 台前县| 特克斯县| 玉溪市| 滨州市| 喜德县| 拉孜县| 厦门市| 分宜县| 凤城市| 吉首市| 绥德县| 旺苍县| 公安县| 武城县| 论坛| 南涧| 宁城县| 根河市| 卓尼县| 南投县| 温州市| 梅河口市|