From d383439c4e696269918bb16b198217eca94d478a Mon Sep 17 00:00:00 2001 From: Ajit Panigrahi Date: Wed, 21 Jun 2023 09:00:54 +0530 Subject: [PATCH] perf: update getUniqueTags func for better efficiency * refactor: getUniqueTags should perform conversions exactly once per tag Previously, the `forEach` loop was spreading the tags list and updating it on every iteration. So for every post, the slugify operation was happening on previously converted data again. Similarly, the last filter operation to remove duplicates was repeated for every post (`O(N * log N)`) instead of checking once at the end (`O(N)`). * feat: Sort the tags in ascending order (lexicographic) As per feedback from: https://github.com/satnaing/astro-paper/pull/78#issuecomment-1593979458 --- src/utils/getUniqueTags.ts | 17 ++++++++--------- 1 file changed, 8 insertions(+), 9 deletions(-) diff --git a/src/utils/getUniqueTags.ts b/src/utils/getUniqueTags.ts index 57a82ed..2e8ffa5 100644 --- a/src/utils/getUniqueTags.ts +++ b/src/utils/getUniqueTags.ts @@ -2,16 +2,15 @@ import { slugifyStr } from "./slugify"; import type { CollectionEntry } from "astro:content"; const getUniqueTags = (posts: CollectionEntry<"blog">[]) => { - let tags: string[] = []; const filteredPosts = posts.filter(({ data }) => !data.draft); - filteredPosts.forEach(post => { - tags = [...tags, ...post.data.tags] - .map(tag => slugifyStr(tag)) - .filter( - (value: string, index: number, self: string[]) => - self.indexOf(value) === index - ); - }); + const tags: string[] = filteredPosts + .flatMap(post => post.data.tags) + .map(tag => slugifyStr(tag)) + .filter( + (value: string, index: number, self: string[]) => + self.indexOf(value) === index + ) + .sort((tagA: string, tagB: string) => tagA.localeCompare(tagB)); return tags; };