@@ -40,6 +40,56 @@ function ratingBelongsToScoreVersion(rating: RatingCategoryRef, version: PageVer
4040 return ratingVersion === version ;
4141}
4242
43+ function categoryScore (
44+ game : { id : number ; categoryAverages : CategoryAverage [ ] } ,
45+ categoryId : number ,
46+ categoryName ?: string ,
47+ ) {
48+ const categoryAverage = game . categoryAverages . find ( ( avg ) =>
49+ categoryId >= 0
50+ ? avg . categoryId === categoryId
51+ : avg . categoryName === categoryName ,
52+ ) ;
53+ return categoryAverage ?. averageScore ?? 0 ;
54+ }
55+
56+ function categoryRatingCount (
57+ game : { id : number ; categoryAverages : CategoryAverage [ ] } ,
58+ categoryId : number ,
59+ categoryName ?: string ,
60+ ) {
61+ const categoryAverage = game . categoryAverages . find ( ( avg ) =>
62+ categoryId >= 0
63+ ? avg . categoryId === categoryId
64+ : avg . categoryName === categoryName ,
65+ ) ;
66+ return categoryAverage ?. ratingCount ?? 0 ;
67+ }
68+
69+ function compareGamesByRawCategoryScore (
70+ a : { id : number ; categoryAverages : CategoryAverage [ ] } ,
71+ b : { id : number ; categoryAverages : CategoryAverage [ ] } ,
72+ categoryId : number ,
73+ categoryName ?: string ,
74+ ) {
75+ const scoreDiff =
76+ categoryScore ( b , categoryId , categoryName ) -
77+ categoryScore ( a , categoryId , categoryName ) ;
78+ if ( scoreDiff !== 0 ) return scoreDiff ;
79+
80+ const countDiff =
81+ categoryRatingCount ( b , categoryId , categoryName ) -
82+ categoryRatingCount ( a , categoryId , categoryName ) ;
83+ if ( countDiff !== 0 ) return countDiff ;
84+
85+ const overallDiff =
86+ categoryScore ( b , - 1 , OVERALL_RATING_CATEGORY_NAME ) -
87+ categoryScore ( a , - 1 , OVERALL_RATING_CATEGORY_NAME ) ;
88+ if ( overallDiff !== 0 ) return overallDiff ;
89+
90+ return a . id - b . id ;
91+ }
92+
4393export async function buildVersionScores ( {
4494 game,
4595 version,
@@ -276,19 +326,18 @@ export async function buildVersionScores({
276326 rankedGames . forEach ( ( entry ) => {
277327 entry . categoryAverages . forEach ( ( category : CategoryAverage ) => {
278328 const rankedGamesInCategory = rankedGames
279- . map ( ( candidate ) => {
280- const categoryAvg = candidate . categoryAverages . find (
281- ( cat : CategoryAverage ) => cat . categoryId === category . categoryId ,
282- ) ;
283- return {
284- gameId : candidate . id ,
285- score : categoryAvg ? categoryAvg . averageScore : 0 ,
286- } ;
287- } )
288- . sort ( ( a , b ) => b . score - a . score ) ;
329+ . slice ( )
330+ . sort ( ( a , b ) =>
331+ compareGamesByRawCategoryScore (
332+ a ,
333+ b ,
334+ category . categoryId ,
335+ category . categoryName ,
336+ ) ,
337+ ) ;
289338
290339 const gamePlacement = rankedGamesInCategory . findIndex (
291- ( rankedGame ) => rankedGame . gameId === entry . id ,
340+ ( rankedGame ) => rankedGame . id === entry . id ,
292341 ) ;
293342
294343 category . placement = gamePlacement + 1 ;
0 commit comments