mirror of
https://github.com/kogakure/website-astro-stefanimhoff.de.git
synced 2026-02-03 20:15:27 +00:00
feat: add helper to sort journal posts
This commit is contained in:
55
src/utils/format-posts.ts
Normal file
55
src/utils/format-posts.ts
Normal file
@@ -0,0 +1,55 @@
|
|||||||
|
import { sortByAlphabet, sortByDate } from '.';
|
||||||
|
|
||||||
|
import type { CollectionEntry } from 'astro:content';
|
||||||
|
|
||||||
|
export const formatPosts = (
|
||||||
|
posts: CollectionEntry<'journal'>[],
|
||||||
|
{
|
||||||
|
removeDrafts = true,
|
||||||
|
removeFuture = true,
|
||||||
|
sortBy = 'date',
|
||||||
|
sortOrder = 'desc',
|
||||||
|
limit,
|
||||||
|
}: {
|
||||||
|
removeDrafts?: boolean;
|
||||||
|
removeFuture?: boolean;
|
||||||
|
sortBy?: 'date' | 'alphabet' | 'random';
|
||||||
|
sortOrder?: 'asc' | 'desc';
|
||||||
|
limit?: number;
|
||||||
|
}
|
||||||
|
): CollectionEntry<'journal'>[] => {
|
||||||
|
const filteredPosts = posts.reduce((acc: CollectionEntry<'journal'>[], post) => {
|
||||||
|
const { date, draft } = post.data;
|
||||||
|
|
||||||
|
// Remove draft content
|
||||||
|
if (removeDrafts && draft) return acc;
|
||||||
|
|
||||||
|
// Remove future content
|
||||||
|
if (removeFuture && new Date(date) > new Date()) return acc;
|
||||||
|
|
||||||
|
acc.push(post);
|
||||||
|
|
||||||
|
return acc;
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
// Sort posts
|
||||||
|
if (sortBy === 'date') {
|
||||||
|
filteredPosts.sort(sortByDate);
|
||||||
|
} else if (sortBy === 'alphabet') {
|
||||||
|
filteredPosts.sort(sortByAlphabet);
|
||||||
|
} else {
|
||||||
|
filteredPosts.sort(() => Math.random() - 0.5);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Sort order
|
||||||
|
if (sortOrder === 'asc') {
|
||||||
|
filteredPosts.reverse();
|
||||||
|
}
|
||||||
|
|
||||||
|
// Limit number of posts
|
||||||
|
if (typeof limit === 'number') {
|
||||||
|
return filteredPosts.slice(0, limit);
|
||||||
|
}
|
||||||
|
|
||||||
|
return filteredPosts;
|
||||||
|
};
|
||||||
@@ -1,6 +1,8 @@
|
|||||||
export * from './date';
|
export * from './date';
|
||||||
|
export * from './format-posts';
|
||||||
export * from './pick-two-random-colors';
|
export * from './pick-two-random-colors';
|
||||||
export * from './remark-reading-time';
|
export * from './remark-reading-time';
|
||||||
|
export * from './sort-by-alphabet';
|
||||||
export * from './sort-by-date';
|
export * from './sort-by-date';
|
||||||
export * from './sort-by-sortkey';
|
export * from './sort-by-sortkey';
|
||||||
export * from './word-count';
|
export * from './word-count';
|
||||||
|
|||||||
3
src/utils/sort-by-alphabet.ts
Normal file
3
src/utils/sort-by-alphabet.ts
Normal file
@@ -0,0 +1,3 @@
|
|||||||
|
export const sortByAlphabet = (a: any, b: any) => {
|
||||||
|
return a.data.title.localeCompare(b.data.title);
|
||||||
|
};
|
||||||
Reference in New Issue
Block a user