From a93db7f417d5102d18a73dd09563933e2e7cbbea Mon Sep 17 00:00:00 2001 From: Dragory <2606411+Dragory@users.noreply.github.com> Date: Sat, 13 Feb 2021 17:43:23 +0200 Subject: [PATCH] counters: make decay accurate over time, even if it's sometimes rounded; don't apply decay of 0 --- backend/src/data/GuildCounters.ts | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/backend/src/data/GuildCounters.ts b/backend/src/data/GuildCounters.ts index 1ec39214..eea1e9f6 100644 --- a/backend/src/data/GuildCounters.ts +++ b/backend/src/data/GuildCounters.ts @@ -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, }, ); }