Improving Similar Post Relevance

Nothing too big, but I tweaked the “Other Posts You May Enjoy” section to sort by number of matches, not just date. Before it found all posts with one or more of the current post’s tags, but didn’t change the default order of reverse chronological. Now it sorts by number of similar tags, then date. So a post with 3 matches from last year will rank higher than a post with 2 from last week. Nothing ground breaking, but hopefully will help surface more relevant posts.

export async function getSimilarPosts (post: CollectionEntry<'posts'>): Promise<CollectionEntry<'posts'>[]> {
	const excludedTags = ['notes', 'links', 'featured', 'videos', 'quotes']
	const similarTags = post.data.tags.filter(tag => !excludedTags.includes(tag))

	return (
		(await getPosts(filteredPost => (
			filteredPost.slug !== post.slug &&
      filteredPost.data.tags.filter(tag => similarTags.includes(tag)).length > 0
		))).map(post => ({
			...post,
			similarTagCount: post.data.tags.filter(tag => similarTags.includes(tag)).length
		})).sort((a, b) => {
			if (a.similarTagCount > b.similarTagCount) return -1
			if (b.similarTagCount > a.similarTagCount) return 1

			if (a.data.pubDate > b.data.pubDate) return -1
			if (a.data.pubDate < b.data.pubDate) return 1

			return 0
		})
	)
}

Other posts you may enjoy!