Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return a default value from a Map?

Tags:

javascript

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
like image 767
1in7billion Avatar asked Apr 29 '16 20:04

1in7billion


People also ask

How do you return a value from a map?

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.

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.

What does the getOrDefault () method on map do?

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.

How do you initialize a map with default value?

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.


1 Answers

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.

Working Example (requires modern JS engine):

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
like image 76
Alexander O'Mara Avatar answered Oct 16 '22 19:10

Alexander O'Mara