1in7billion 1in7billion - 7 months ago 16
Javascript Question

How to return a default value from a Map?

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

Answer

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