- Mastering Immutable.js
- Adam Boduch
- 202字
- 2021-07-08 10:30:13
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.
推薦閱讀
- Advanced Quantitative Finance with C++
- JavaScript 網頁編程從入門到精通 (清華社"視頻大講堂"大系·網絡開發視頻大講堂)
- C#程序設計教程
- PHP+MySQL網站開發項目式教程
- 微服務從小白到專家:Spring Cloud和Kubernetes實戰
- Mastering React
- .NET 4.5 Parallel Extensions Cookbook
- QGIS 2 Cookbook
- Xamarin Blueprints
- Learning Nessus for Penetration Testing
- 30天學通C#項目案例開發
- 游戲設計的底層邏輯
- Joomla!Search Engine Optimization
- JBoss AS 7 Development
- 精益軟件開發管理之道