Map.prototype.getOrDefault

Given an array of numbers, I want to build a map in which the key is the number, value is the occurrence time of the number.
Input: [1, 2, 2, 3, 3, 3]
Output: Map(3) {1 => 1, 2 => 2, 3 => 3}

In Java, we could write our program as:

HashMap<Integer, Integer> map = new HashMap<>();
for (int num : nums) {
   map.put(num, map.getOrDefault(num, 0) + num);
}

The key is getOrDefault method on HashMap, see Java API doc for detail: Map (Java Platform SE 8 )

In JavaScript, we could write as:

const map = new Map();
for (const num of nums) {
  map.set(num, (map.get(num) ?? 0) + 1);
};

The javascript version have two problem in my opinion:

  1. map.get(num) ?? 0 is less readable to map.getOrDefault(num, 0)
  2. (map.get(num) ?? 0) + 1 is more prone to mistake

On the first try, I write the following program:

const map = new Map();
for (const num of nums) {
  map.set(num, map.get(num) ?? 0 + 1);
};

If we input [1, 2, 2, 3, 3, 3], the output is Map(3) {1 => 1, 2 => 1, 3 => 1}. This is because map.get(num) ?? 0 + 1 is evaluated as map.get(num) ?? (0 + 1) in javascript.

So I am wondering if we could add Map.prototype.getOrDefault to javascript, so that we could rewrite the above program to:

const map = new Map();
for (const num of nums) {
  map.set(num, map.getOrDefault(num, 0) + 1);
};

Hi @F3n67u

It sounds like you would be interested in this existing stage 2 proposal: