47 lines
2.5 KiB
JavaScript
47 lines
2.5 KiB
JavaScript
// Frozen pre-optimization behavior, used for output equivalence and CPU benchmarks.
|
|
class Baseline {
|
|
diversifyRankedPosts(ranked) {
|
|
const remaining = [...ranked];
|
|
const result = [];
|
|
const authorCounts = new Map();
|
|
const typeCounts = new Map();
|
|
const hashtagCounts = new Map();
|
|
while (remaining.length) {
|
|
let bestIndex = 0;
|
|
let bestAdjustedScore = Number.NEGATIVE_INFINITY;
|
|
for (let index = 0; index < remaining.length; index += 1) {
|
|
const entry = remaining[index];
|
|
const authorId = this.extractEntityId(entry.post.authorId);
|
|
const postType = String(entry.post.postType ?? '');
|
|
const hashtags = Array.isArray(entry.post.hashtags)
|
|
? entry.post.hashtags.map((tag) => String(tag).toLowerCase())
|
|
: [];
|
|
const previousAuthorId = result.length
|
|
? this.extractEntityId(result[result.length - 1].post.authorId)
|
|
: '';
|
|
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 (adjusted > bestAdjustedScore) {
|
|
bestAdjustedScore = adjusted;
|
|
bestIndex = index;
|
|
}
|
|
}
|
|
const [selected] = remaining.splice(bestIndex, 1);
|
|
const authorId = this.extractEntityId(selected.post.authorId);
|
|
const postType = String(selected.post.postType ?? '');
|
|
authorCounts.set(authorId, (authorCounts.get(authorId) ?? 0) + 1);
|
|
typeCounts.set(postType, (typeCounts.get(postType) ?? 0) + 1);
|
|
for (const hashtag of Array.isArray(selected.post.hashtags) ? selected.post.hashtags : []) {
|
|
const normalized = String(hashtag).toLowerCase();
|
|
hashtagCounts.set(normalized, (hashtagCounts.get(normalized) ?? 0) + 1);
|
|
}
|
|
result.push({ ...selected, score: bestAdjustedScore });
|
|
}
|
|
return result;
|
|
}
|
|
}
|
|
module.exports = Baseline.prototype.diversifyRankedPosts;
|