Get or set element in a Javascript ES6 Map?

纵然是瞬间 提交于 2019-12-11 12:41:14

问题


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.


回答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.



来源:https://stackoverflow.com/questions/37134851/get-or-set-element-in-a-javascript-es6-map

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!