JavaScript - Map() increment value

23,251

Solution 1

The way you do it is fine. That is how you need to do it if you are working with primitive values. If you want to avoid the call to map.set, then you must revert to a reference to a value. In other words, then you need to store an object, not a primitive:

let map = new Map();
map.set("a", {val: 1});

And then incrementing becomes:

map.get("a").val++;

Solution 2

for modern js, you could do this:

map.set("a", (map.get("a") ?? 0) + 1)

Solution 3

Map does not have a built-in feature that increments a value. However, since JavaScript constructs can be modified you can actually do that yourself:

let map = new Map()
// Modify your map
map.constructor.prototype.increment = function (key) {
  this.has(key) && this.set(key, this.get(key) + 1)
}
map.constructor.prototype.decrement = function (key) {
  this.has(key) && this.set(key, this.get(key) - 1)
}

// Now you can use it right away
map.set('test', 1)
map.increment('test')
map.increment('test')
map.decrement('test')
console.log(map.get('test')) // returns 2

To make this easier in the future, you can abstract it into a utility:

class CyborgMap extends Map {
  constructor() {
    super()
    
    this.constructor.prototype.increment = function (key) {
      this.has(key) && this.set(key, this.get(key) + 1)
    }
    this.constructor.prototype.decrement = function (key) {
      this.has(key) && this.set(key, this.get(key) - 1)
    }
  }
}

Now import it and use it:

import { CyborgMap } from "./utils"

let map = new CyborgMap()
map.set('test', 1)
map.increment('test')
map.increment('test')
map.decrement('test')
console.log(map.get('test')) // returns 2

Solution 4

In map, if you didn't find any element it will give undefined. So, we can do the increment with the below code:

map.set("a", map.get("a") == undefined ? 1 : map.get("a") + 1);

or just

map.set('a', map.get('a') + 1 || 1);
Share:
23,251
EDJ
Author by

EDJ

Updated on November 09, 2021

Comments

  • EDJ
    EDJ over 2 years

    I have a map as follows:

    let map = new Map();
    map.set("a", 1);
    //Map is now {'a' => 1}
    

    I want to change the value of a to 2, or increment it: map.get("a")++;

    Currently, I am using the following:

    map.set("a", (map.get("a"))+1);
    

    However, this does not feel right. Does anyone know a cleaner way of doing this? Is it possible?