counters: make decay accurate over time, even if it's sometimes rounded; don't apply decay of 0

This commit is contained in:
Dragory 2021-02-13 17:43:23 +02:00
parent 39448a4213
commit a93db7f417
No known key found for this signature in database
GPG key ID: 5F387BA66DF8AAC1

View file

@ -184,8 +184,6 @@ export class GuildCounters extends BaseGuildRepository {
}
async decay(id: number, decayPeriodMs: number, decayAmount: number) {
const now = moment.utc().format(DBDateFormat);
const counter = (await this.counters.findOne({
where: {
id,
@ -198,6 +196,15 @@ export class GuildCounters extends BaseGuildRepository {
}
const decayAmountToApply = Math.round((diffFromLastDecayMs / decayPeriodMs) * decayAmount);
if (decayAmountToApply === 0) {
return;
}
// Calculate new last_decay_at based on the rounded decay amount we applied. This makes it so that over time, the decayed amount will stay accurate, even if we round some here.
const newLastDecayDate = moment
.utc(counter.last_decay_at)
.add((decayAmountToApply / decayAmount) * decayPeriodMs, "ms")
.format(DBDateFormat);
const rawUpdate =
decayAmountToApply >= 0
@ -218,7 +225,7 @@ export class GuildCounters extends BaseGuildRepository {
id,
},
{
last_decay_at: now,
last_decay_at: newLastDecayDate,
},
);
}