Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Map default value

I'm looking for something like default value for Map.

m = new Map();
//m.setDefVal([]); -- how to write this line???
console.log(m[whatever]);

Now the result is Undefined but I want to get empty array [].

like image 609
Newbie Avatar asked Jul 13 '18 06:07

Newbie


People also ask

What is default value of MAP in Java?

Since the hashmap does not contain any mapping for key 4 . Hence, the default value Not Found is returned. Note: We can use the HashMap containsKey() method to check if a particular key is present in the hashmap.

Is map ordered by default?

By default, a Map in C++ is sorted in increasing order based on its key.

How do you initialize a map with 0?

What exactly do you want to initialize to zero? map's default constructor creates empty map. You may increase map's size only by inserting elements (like m["str1"]=0 or m. insert(std::map<std::string,int>::value_type("str2",0)) ).

What is default value of INT in C++?

Variables of type "int" have a default value of 0.


2 Answers

First of all to answer the question regarding the standard Map: Javascript Map as proposed in ECMAScript 2015 does not include a setter for default values. This, however, does not restrain you from implementing the function yourself.

If you just want to print a list, whenever m[whatever] is undefined, you can just: console.log(m.get('whatever') || []); as pointed out by Li357 in his comment.

If you want to reuse this functionality, you could also encapsulate this into a function like:

function getMapValue(map, key) {
    return map.get(key) || [];
}

// And use it like:
const m = new Map();
console.log(getMapValue(m, 'whatever'));

If this, however, does not satisfy your needs and you really want a map that has a default value you can write your own Map class for it like:

class MapWithDefault extends Map {
  get(key) {
    if (!this.has(key)) {
      this.set(key, this.default());
    }
    return super.get(key);
  }
  
  constructor(defaultFunction, entries) {
    super(entries);
    this.default = defaultFunction;
  }
}

// And use it like:
const m = new MapWithDefault(() => []);
m.get('whatever').push('you');
m.get('whatever').push('want');
console.log(m.get('whatever')); // ['you', 'want']
like image 146
friedow Avatar answered Sep 20 '22 13:09

friedow


As of 2022, Map.prototype.emplace has reached stage 2.

As it says on the proposal page, a polyfill is available in the core-js library.

like image 21
James Avatar answered Sep 17 '22 13:09

James