Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's a better way to initialize with zero or increment for objects?

I'm writing analytics and I have to initialize counter counts for (keys) hours, days, weeks, years so as to get frequency of user activity. I need to create a hit count for respective time and increment accordingly. Visits are fed via a loop. I have this working but I'm not sure if the code below is ideal to do so.

if(!analytics.users[message.user].counts.hourly[hour]) {
    analytics.users[message.user].counts.hourly[hour] = 0;
}
analytics.users[message.user].counts.hourly[hour] += 1;

if(!analytics.users[message.user].counts.daily[day]) {
    analytics.users[message.user].counts.daily[day] = 0;
}
analytics.users[message.user].counts.daily[day] += 1;

...

I've tried the x = x + 1 || 0 method but that hasn't worked. Also, is there a way I can set up a function for this?

like image 556
Zack Webster Avatar asked Jan 30 '26 23:01

Zack Webster


1 Answers

You could use a function which take the object and the key and perfoms the check and update.

function increment(object, key) {
    if (!object[key]) object[key] = 0;
    ++object[key];
}

Call with

increment(analytics.users[message.user].counts.hourly, hour);
like image 58
Nina Scholz Avatar answered Feb 01 '26 14:02

Nina Scholz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!