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