Search code examples
javascriptalgorithmoptimizationobject-literal

What's a clean way to use an object literal to track several (unknown) counts?


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.


Solution

  • 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;
    }