- Mastering Immutable.js
- Adam Boduch
- 206字
- 2021-07-08 10:30:12
Replacing collections with new instances
The simplest way to empty a collection is to replace it with a new instance, as shown here:
const empty = (collection) => {
if (collection instanceof List) {
return List();
}
if (collection instanceof Map) {
return Map();
}
return null;
};
const myList = List.of(1, 2);
const myMap = Map.of('one', 1, 'two', 2);
const myEmptyList = empty(myList);
const myEmptyMap = empty(myMap);
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 {}
We've created a little helper function called empty(). The idea is that it accepts either a list or map as its argument. Depending on the type of collection, a new instance is returned. Then, we can assign this new value to myEmptyList. Remember, as long as myList is referenced, it will never be garbage-collected. If you don't want this to happen, you could store the collection in a variable instead of in a constant. Then, empty() can simply replace the old collection:
var myList = List.of(1, 2);
myList = empty(myList);
Now, the garbage collector can pick up the first collection with the values 1 and 2.
推薦閱讀
- PostgreSQL Cookbook
- Cocos2d-x游戲開(kāi)發(fā):手把手教你Lua語(yǔ)言的編程方法
- 算法精粹:經(jīng)典計(jì)算機(jī)科學(xué)問(wèn)題的Java實(shí)現(xiàn)
- 編寫(xiě)高質(zhì)量代碼:改善Python程序的91個(gè)建議
- Elastic Stack應(yīng)用寶典
- Internet of Things with ESP8266
- 零基礎(chǔ)C#學(xué)習(xí)筆記
- 金融商業(yè)數(shù)據(jù)分析:基于Python和SAS
- 從零開(kāi)始學(xué)Unity游戲開(kāi)發(fā):場(chǎng)景+角色+腳本+交互+體驗(yàn)+效果+發(fā)布
- H5頁(yè)面設(shè)計(jì)與制作(全彩慕課版·第2版)
- 三步學(xué)Python
- HTML 5與CSS 3權(quán)威指南(第4版·上冊(cè))
- Storm Real-Time Processing Cookbook
- Mastering Wireless Penetration Testing for Highly Secured Environments
- MATLAB程序設(shè)計(jì)及應(yīng)用