0

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

3
  • 4
    Is there a more concise way no (excluding the obvious - Map.prototype.incr = function(x) { this.set(x, this.get(x) + 1); }) Commented Feb 21, 2018 at 3:28
  • I think the real question is... Why exactly you need to use a Map object like an array..? Commented May 5, 2018 at 19:09
  • For example, count each item's num Commented May 6, 2018 at 15:37

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.