Skip to content Skip to sidebar Skip to footer

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): // g

Solution 1:

The lookup has to happen anyway, it doesn't matter much if you avoid it, at least until the engines are optimized much more.

But Map.has is a nicer solution and should be a bit faster than Map.get(). For example:

myMap.has(myKey) ? true : myMap.set(myKey, myValue)

Performance should be irrelevant on this level unless you're google-scale. But if it's a serious bottleneck, an Array should still be faster than Map/Set for the forseeable future.

Solution 2:

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] || newSet()).add(v) ? a : a, {})

With Map it should have become

.reduce((a, [k, v]) => (a.has(k) ? a : a.set(k, newSet())).get(k).add(v) ? a : a, newMap())

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, newSet()).add(v) ? a : a, newMap())

Post a Comment for "Get Or Set Element In A Javascript Es6 Map?"