Skip to content

Commit f1bff82

Browse files
committed
fix: not accounting for when nobody votes
it handled it by just ignoring the string if there was a division by zero but that's a bit of a cop-out
1 parent 7ac0dee commit f1bff82

2 files changed

Lines changed: 14 additions & 10 deletions

File tree

resources/strings.json

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -145,7 +145,8 @@
145145
"results_denied": "Failed community vote and will not be added.",
146146
"instapassed": "Instapassed by %USER%",
147147
"invalidated": "Invalidated by %USER%",
148-
"upvote_percentage": "(%d% upvoted)"
148+
"upvote_percentage": "(%d% upvoted)",
149+
"no_votes": "(Nobody voted…)"
149150
},
150151
"footer": {
151152
"texture_edit": "Reference | Submitted | Current",

src/submission/results/sendResults.ts

Lines changed: 12 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -107,13 +107,16 @@ export function sendMessage(
107107
* @returns formatted string (or an empty string if not possible)
108108
*/
109109
export function getPercentage(upvotes: number, downvotes: number) {
110-
const upvotePercentage =
111-
((upvotes - DEFAULT_REACTION_COUNT) * 100) /
112-
(upvotes - DEFAULT_REACTION_COUNT + (downvotes - DEFAULT_REACTION_COUNT));
113-
// handle division by zero and cache issues
114-
if (isNaN(upvotePercentage) || !isFinite(upvotePercentage)) return "";
115-
return strings.submission.status.upvote_percentage.replace(
116-
"%d",
117-
String(Number(upvotePercentage.toFixed(2))),
118-
);
110+
// normalize
111+
upvotes -= DEFAULT_REACTION_COUNT;
112+
downvotes -= DEFAULT_REACTION_COUNT;
113+
114+
// prevent division by zero if nobody voted
115+
if (upvotes === 0 && downvotes === 0) return strings.submission.status.no_votes;
116+
117+
const upvoteRatio = upvotes / (upvotes + downvotes);
118+
119+
// re-cast to number to remove unnecessary decimals (100.00 -> 100)
120+
const upvotePercentage = Number((upvoteRatio * 100).toFixed(2));
121+
return strings.submission.status.upvote_percentage.replace("%d", String(upvotePercentage));
119122
}

0 commit comments

Comments
 (0)