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

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.
主站蜘蛛池模板: 确山县| 佳木斯市| 鄱阳县| 临清市| 平湖市| 墨竹工卡县| 仁怀市| 东阿县| 石首市| 松阳县| 石嘴山市| 崇义县| 古蔺县| 固阳县| 监利县| 明溪县| 巴东县| 肇庆市| 临夏市| 库伦旗| 门源| 东港市| 安陆市| 江津市| 正安县| 盐池县| 张掖市| 库尔勒市| 台南县| 家居| 宝丰县| 宜章县| 台山市| 上犹县| 南陵县| 和田县| 若羌县| 宜阳县| 恩施市| 太仆寺旗| 深泽县|