0

Given the following code, there is the variable counts that counts the amount of times the function functionThatGivesSomeKnownOrUnknownStatus gives each status.

const counts = {};

for (let i = 0; i < 100; i++) {
    const status = functionThatGivesSomeKnownOrUnknownStatus();

    counts[status] = counts[status] ? counts[status] + 1 : 1;
}

The part I don't like is this line counts[status] = counts[status] ? counts[status] + 1 : 1;, is there a way to make it shorter and simpler/less redundant/cleaner? This is a node script so ES6/7 solutions are welcome.

One way could be initializing the counts literal with the keys already set to 0, but I don't know the status the function can give.


Tried to make the title as clear and concise as possible, if it can be improved, feel free to edit it.

Alvaro Castro
  • 811
  • 1
  • 9
  • 26
  • 2
    `counts[status] = (counts[status] || 0) + 1` saves one repetition. – Ry- Apr 01 '19 at 18:21
  • A possible approach for more semantic is using a [default dict](https://stackoverflow.com/questions/19127650/defaultdict-equivalent-in-javascript) with value 0: – juvian Apr 01 '19 at 18:23
  • (Don’t implement a default dict with proxies like in the top answer to that question, though. It’s much cleaner to do it on top of `Map`.) – Ry- Apr 01 '19 at 18:25

1 Answers1

0

As @Ry commented, I ended up using this solution:

counts[status] = (counts[status] || 0) + 1;

Inside the code:

const counts = {};

for (let i = 0; i < 100; i++) {
    const status = functionThatGivesSomeKnownOrUnknownStatus();

    counts[status] = (counts[status] || 0) + 1;
}
Alvaro Castro
  • 811
  • 1
  • 9
  • 26