Using the ES6 Proxy object it is possible to return a default value when a property does not exist in a plain object.
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Proxy
How to do this with a Map? I have tried the following code but the default value is always returned:
var map = new Map ([
[1, 'foo'], // default
[2, 'bar'],
[3, 'baz'],
]);
var mapProxy = new Proxy(map, {
get: function(target, id) {
return target.has(id) ? target.get(id) : target.get(1);
},
});
console.log( mapProxy[3] ); // foo
The get() method of Map interface in Java is used to retrieve or fetch the value mapped by a particular key mentioned in the parameter. It returns NULL when the map contains no such mapping for the key.
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.
The getOrDefault(Object key, V defaultValue) method of Map interface, implemented by HashMap class is used to get the value mapped with specified key. If no value is mapped with the provided key then the default value is returned.
To initialize the map with a random default value below is the approach: Approach: Declare a structure(say struct node) with a default value. Initialize Map with key mapped to struct node.
That's because your map keys are numbers, but the proxy property name is always a string. You would need to cast id
to a number first.
var map = new Map ([
[1, 'foo'], // default
[2, 'bar'],
[3, 'baz'],
]);
var mapProxy = new Proxy(map, {
get: function(target, id) {
// Cast id to number:
id = +id;
return target.has(id) ? target.get(id) : target.get(1);
},
});
console.log( mapProxy[3] ); // baz
console.log( mapProxy[10] ); // foo
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