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

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.
主站蜘蛛池模板: 宜川县| 福海县| 石嘴山市| 张掖市| 玛曲县| 呼和浩特市| 大冶市| 蒲江县| 莎车县| 普定县| 海口市| 龙里县| 永修县| 桂东县| 济宁市| 博兴县| 台前县| 二连浩特市| 荥经县| 嘉禾县| 宁远县| 西城区| 昭平县| 东海县| 南郑县| 满洲里市| 玛沁县| 屏山县| 曲沃县| 赤水市| 磐石市| 临西县| 进贤县| 大姚县| 岳普湖县| 泸西县| 奇台县| 神池县| 东乡县| 罗源县| 长垣县|