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

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.
主站蜘蛛池模板: 景东| 宿州市| 临沧市| 乐业县| 英超| 砀山县| 保靖县| 太仆寺旗| 屏东县| 博兴县| 顺义区| 钟祥市| 大港区| 武安市| 乐清市| 济源市| 会理县| 益阳市| 湟源县| 衡水市| 建宁县| 罗山县| 远安县| 含山县| 塘沽区| 陆川县| 福州市| 伊宁县| 冷水江市| 威海市| 察哈| 武陟县| 深水埗区| 措勤县| 南川市| 嘉峪关市| 岳阳市| 嘉定区| 什邡市| 陈巴尔虎旗| 邯郸市|