mirror of
https://github.com/ChenQihan666/MyBlog-Next.git
synced 2026-08-14 11:29:33 +08:00
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:
@@ -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;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user