Fix sorting of photos with equal likes so they are properly randomized instead of grouped by ID

This commit is contained in:
Jannik committed 2026-10-01 06:36:16 +02:00
1 parent 0f4340e214
commit 7261663863
1 file changed
+24 -19
+24 -19
View File
@@ -20,31 +20,36 @@ export function getShuffledItemIds(metadata: any[], seed: number) {
return b.id - a.id; // Fallback to newest first return b.id - a.id; // Fallback to newest first
}); });
// Sort normal items by likes DESC, then newest first // Group normal items by number of likes
normalItems.sort((a, b) => { const groupedByLikes = new Map<number, any[]>();
const likesA = a._count?.likes || 0; for (const item of normalItems) {
const likesB = b._count?.likes || 0; const likes = item._count?.likes || 0;
if (likesA !== likesB) return likesB - likesA; if (!groupedByLikes.has(likes)) {
return b.id - a.id; groupedByLikes.set(likes, []);
}); }
groupedByLikes.get(likes)!.push(item);
// 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));
} }
// 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); 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)); 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 // Combine and return IDs
const combined = [...fixedItems, ...chunks.flat()]; const combined = [...fixedItems, ...shuffledNormalItems];
return combined.map(m => m.id); return combined.map(m => m.id);
} }