From 726166386394ad5d650adafcb1687b0f9363c667 Mon Sep 17 00:00:00 2001 From: orfelorfel23 Date: Thu, 1 Oct 2026 06:36:16 +0200 Subject: [PATCH] Fix sorting of photos with equal likes so they are properly randomized instead of grouped by ID --- src/lib/sorting.ts | 43 ++++++++++++++++++++++++------------------- 1 file changed, 24 insertions(+), 19 deletions(-) diff --git a/src/lib/sorting.ts b/src/lib/sorting.ts index edd98a7..65db573 100644 --- a/src/lib/sorting.ts +++ b/src/lib/sorting.ts @@ -20,31 +20,36 @@ export function getShuffledItemIds(metadata: any[], seed: number) { return b.id - a.id; // Fallback to newest first }); - // Sort normal items by likes DESC, then newest first - normalItems.sort((a, b) => { - const likesA = a._count?.likes || 0; - const likesB = b._count?.likes || 0; - if (likesA !== likesB) return likesB - likesA; - return b.id - a.id; - }); - - // Chunk normal items into 10% blocks - const chunkSize = Math.max(1, Math.ceil(normalItems.length * 0.1)); - const chunks: any[][] = []; - for (let i = 0; i < normalItems.length; i += chunkSize) { - chunks.push(normalItems.slice(i, i + chunkSize)); + // Group normal items by number of likes + const groupedByLikes = new Map(); + for (const item of normalItems) { + const likes = item._count?.likes || 0; + if (!groupedByLikes.has(likes)) { + groupedByLikes.set(likes, []); + } + groupedByLikes.get(likes)!.push(item); } - // Shuffle each chunk using the seed + // Sort the like counts descending + const sortedLikeCounts = Array.from(groupedByLikes.keys()).sort((a, b) => b - a); + + const shuffledNormalItems: any[] = []; const prng = mulberry32(seed); - chunks.forEach(chunk => { - for (let i = chunk.length - 1; i > 0; i--) { + + // For each group of likes, shuffle the items and add to the final list + for (const likes of sortedLikeCounts) { + const group = groupedByLikes.get(likes)!; + + // Shuffle the group using the seed + for (let i = group.length - 1; i > 0; i--) { const j = Math.floor(prng() * (i + 1)); - [chunk[i], chunk[j]] = [chunk[j], chunk[i]]; + [group[i], group[j]] = [group[j], group[i]]; } - }); + + shuffledNormalItems.push(...group); + } // Combine and return IDs - const combined = [...fixedItems, ...chunks.flat()]; + const combined = [...fixedItems, ...shuffledNormalItems]; return combined.map(m => m.id); }