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 [].
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.
By default, a Map in C++ is sorted in increasing order based on its key.
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)) ).
Variables of type "int" have a default value of 0.
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']
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With