js how to implement map[index]++ concisely

前端 未结 1 1063
生来不讨喜
生来不讨喜 2020-12-20 09:30

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 i

相关标签:
1条回答
  • 2020-12-20 09:37

    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.

    0 讨论(0)
提交回复
热议问题