How to return the default value from the map?

Using the ES6 Proxy object, you can return the default value when the property does not exist in a regular object.

https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Proxy

How to do this using a map? I 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 
+6
source share
2 answers

This is because your card keys are numbers, but the name of the proxy property is always a string. You will need to give id first number.

Working example (requires a 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 
+5
source

In Scala, cards are monos with the getOrElse method. If the monad (container) does not contain a value, its get method fails with an exception, but getOrElse allows the user to write infallible code

 Map.prototype.getOrElse = function(key, value) { return this.has(key) ? this.get(key) : value } var map = new Map ([[1, 'foo'], [2, 'bar'], [3, 'baz']]); [map.get(1), map.getOrElse(10, 11)]; // gives 11 

Another option is to expand your maps withDefaultValue method

 //a copy of map will have a default value in its get method Map.prototype.withDefaultValue = function(defaultValue) { const result = new Map([...this.entries()]); const getWas = result.get; result.get = (key) => result.has(key) ? getWas.call(this, key) : defaultValue; return result } map.withDefaultValue(12).get(10) // gives 12 

This is the way it is done in Scala. Or at least it looks like this.

-one
source

All Articles