43 lines
2.0 KiB
JavaScript
43 lines
2.0 KiB
JavaScript
// Frozen immediately preceding ranking scan, for like-for-like CPU comparisons.
|
|
module.exports = function diversifyRankedPosts(ranked, take = ranked.length) {
|
|
const remaining = ranked.map((entry) => ({
|
|
entry,
|
|
authorId: this.extractEntityId(entry.post.authorId),
|
|
postType: String(entry.post.postType ?? ''),
|
|
hashtags: Array.isArray(entry.post.hashtags)
|
|
? entry.post.hashtags.map((tag) => String(tag).toLowerCase()) : [],
|
|
selected: false,
|
|
}));
|
|
const result = [];
|
|
const authorCounts = new Map(), typeCounts = new Map(), hashtagCounts = new Map();
|
|
let previousAuthorId = '';
|
|
const target = Math.min(ranked.length, take);
|
|
while (result.length < target) {
|
|
let bestIndex = -1, bestAdjustedScore = -Infinity;
|
|
for (let index = 0; index < remaining.length; index += 1) {
|
|
const candidate = remaining[index];
|
|
if (candidate.selected) continue;
|
|
const { entry, authorId, postType, hashtags } = candidate;
|
|
const authorPenalty = (authorCounts.get(authorId) ?? 0) * 12;
|
|
const consecutivePenalty = authorId && authorId === previousAuthorId ? 22 : 0;
|
|
const typePenalty = Math.max(0, (typeCounts.get(postType) ?? 0) - 1) * 2.5;
|
|
const hashtagPenalty = Math.min(8,
|
|
hashtags.reduce((sum, tag) => sum + (hashtagCounts.get(tag) ?? 0) * 0.75, 0));
|
|
const adjusted = entry.score - authorPenalty - consecutivePenalty - typePenalty - hashtagPenalty;
|
|
if (bestIndex === -1 || adjusted > bestAdjustedScore) {
|
|
bestAdjustedScore = adjusted;
|
|
bestIndex = index;
|
|
}
|
|
}
|
|
const selected = remaining[bestIndex];
|
|
selected.selected = true;
|
|
const { authorId, postType, hashtags } = selected;
|
|
authorCounts.set(authorId, (authorCounts.get(authorId) ?? 0) + 1);
|
|
typeCounts.set(postType, (typeCounts.get(postType) ?? 0) + 1);
|
|
for (const hashtag of hashtags) hashtagCounts.set(hashtag, (hashtagCounts.get(hashtag) ?? 0) + 1);
|
|
previousAuthorId = authorId;
|
|
result.push({ ...selected.entry, score: bestAdjustedScore });
|
|
}
|
|
return result;
|
|
};
|