Skip to content

Commit

Permalink
fix: rounding issues causing daily leaderboard to be out of order som…
Browse files Browse the repository at this point in the history
  • Loading branch information
fehmer authored Feb 24, 2025
1 parent 73182d4 commit 7be66e9
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 2 deletions.
14 changes: 14 additions & 0 deletions backend/__tests__/utils/misc.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,20 @@ describe("Misc Utils", () => {
timestamp: 1653591901000,
expectedScore: 1196200960717699,
},
{
wpm: 196.205,
acc: 96.075,
timestamp: 1653591901000,
expectedScore: 1196210960817699,
},
{
// this one is particularly important - in JS 154.39 * 100 is equal to 15438.999999999998
// thanks floating point errors!
wpm: 154.39,
acc: 96.14,
timestamp: 1740333827000,
expectedScore: 1154390961421373,
},
];

_.each(testCases, ({ wpm, acc, timestamp, expectedScore }) => {
Expand Down
6 changes: 4 additions & 2 deletions backend/src/utils/misc.ts
Original file line number Diff line number Diff line change
Expand Up @@ -67,8 +67,10 @@ export function matchesAPattern(text: string, pattern: string): boolean {
}

export function kogascore(wpm: number, acc: number, timestamp: number): number {
const normalizedWpm = Math.floor(wpm * 100);
const normalizedAcc = Math.floor(acc * 100);
// its safe to round after multiplying by 100 (99.99 * 100 rounded will be 9999 not 100)
// rounding is necessary to protect against floating point errors
const normalizedWpm = Math.round(wpm * 100);
const normalizedAcc = Math.round(acc * 100);

const padAmount = 100000;
const firstPart = (padAmount + normalizedWpm) * padAmount;
Expand Down

0 comments on commit 7be66e9

Please sign in to comment.