Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
500 views
in Technique[技术] by (71.8m points)

javascript - js how to implement map[index]++ concisely

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]++

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...