js how to implement map[index]++ concisely

帅比萌擦擦* 提交于 2019-12-18 07:24:33

问题


With Array, I can use array[index]++

But with Map, I only know map.set(index,map.get(index)+1)

I think it looks bad, and if index is a long name function, I have to split it into two lines.

Is there a more concise way to implement map[index]++


回答1:


I could only suggest a helper function, like

function update(map, key, fn) {
    return map.set(key, fn(map.get(key), key));
}

update(table, index, i=>i+1);

There is no syntactic sugar for assignments, and therefore no shorthand assignments either.


If your keys are strings, you could employ a Proxy with suitable traps to disguise the update as a property access.

const mapMethods = {
    has: Function.prototype.call.bind(Map.prototype.has),
    get: Function.prototype.call.bind(Map.prototype.get),
    set: Function.prototype.call.bind(Map.prototype.set),
};
function asObject(map) {
    return new Proxy(map, mapMethods);
}

asObject(table)[index]++;

Disclaimer: Please don't do that. It's scary.



来源:https://stackoverflow.com/questions/48897716/js-how-to-implement-mapindex-concisely

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