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

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.
主站蜘蛛池模板: 阜新| 从化市| 象山县| 兴国县| 公主岭市| 鄂托克前旗| 漳平市| 浦县| 西乌珠穆沁旗| 罗甸县| 鄂托克前旗| 东源县| 永春县| 巴塘县| 龙胜| 阿勒泰市| 饶平县| 铜梁县| 乌兰县| 中卫市| 武安市| 塘沽区| 北票市| 靖宇县| 舟山市| 新昌县| 扎兰屯市| 岱山县| 常熟市| 九台市| 醴陵市| 施秉县| 钦州市| 建宁县| 大荔县| 平度市| 论坛| 察哈| 玉屏| 章丘市| 清涧县|