Defaultdict equivalent in javascript

前端 未结 5 1205
小蘑菇
小蘑菇 2020-12-29 22:32

In python you can have a defaultdict(int) which stores int as values. And if you try to do a \'get\' on a key which is not present in the dictionary you get zero as default

5条回答
  •  盖世英雄少女心
    2020-12-29 23:21

    Check out pycollections.js:

    var collections = require('pycollections');
    
    var dd = new collections.DefaultDict(function(){return 0});
    console.log(dd.get('missing'));  // 0
    
    dd.setOneNewValue(987, function(currentValue) {
      return currentValue + 1;
    });
    
    console.log(dd.items()); // [[987, 1], ['missing', 0]]
    

提交回复
热议问题