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)];
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.
source share