'Get or set element in a Javascript ES6 Map?
Is it possible to find or add an element in one step in a Javascript Map?
I would like to do the following in one step (to avoid looking twice for the right place of the key):
// get the value if the key exists, set a default value otherwise
let aValue = aMap.get(aKey)
if(aValue == null) {
aMap.set(aKey, aDefaultValue)
}
Instead I would like to search for the key only once.
In c++, one can use std::map::insert() or std::map::lower_bound()
In javascript the code could look like this:
let iterator = aMap.getPosition(aKey)
let aValue = aMap.getValue(iterator)
if(aValue == null)
{
aMap.setWithHint(aKey, aValue, iterator)
}
or
let aValue = aMap.getOrSet(aKey, aDefaultValue)
I suppose that it is not possible, but I want to make sure I am correct. Also I am interested in knowing why it is not possible while it is an important feature.
Solution 1:[1]
I personally ended up changing my Map to a simple Object. That allows to write a reduce (that groups entries into a Map of Sets) like this:
.reduce((a, [k, v]) => (a[k] = a[k] || new Set()).add(v) ? a : a, {})
With Map it should have become
.reduce((a, [k, v]) => (a.has(k) ? a : a.set(k, new Set())).get(k).add(v) ? a : a, new Map())
That feels little too cumbersome for this purpose.
I agree that something like this would be ideal if ever supported:
.reduce((a, [k, v]) => a.getOrSet(k, new Set()).add(v) ? a : a, new Map())
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Jamby |
