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
This commit is contained in:
Ajit Panigrahi
2023-06-21 09:00:54 +05:30
committed by GitHub
parent d48d77c4b5
commit d383439c4e
+8 -9
View File
@@ -2,16 +2,15 @@ import { slugifyStr } from "./slugify";
import type { CollectionEntry } from "astro:content"; import type { CollectionEntry } from "astro:content";
const getUniqueTags = (posts: CollectionEntry<"blog">[]) => { const getUniqueTags = (posts: CollectionEntry<"blog">[]) => {
let tags: string[] = [];
const filteredPosts = posts.filter(({ data }) => !data.draft); const filteredPosts = posts.filter(({ data }) => !data.draft);
filteredPosts.forEach(post => { const tags: string[] = filteredPosts
tags = [...tags, ...post.data.tags] .flatMap(post => post.data.tags)
.map(tag => slugifyStr(tag)) .map(tag => slugifyStr(tag))
.filter( .filter(
(value: string, index: number, self: string[]) => (value: string, index: number, self: string[]) =>
self.indexOf(value) === index self.indexOf(value) === index
); )
}); .sort((tagA: string, tagB: string) => tagA.localeCompare(tagB));
return tags; return tags;
}; };