utils for articles
This commit is contained in:
76
src/blog/utils/articles.ts
Normal file
76
src/blog/utils/articles.ts
Normal file
@@ -0,0 +1,76 @@
|
||||
import {
|
||||
ArticleModel,
|
||||
ArticleRepoModel
|
||||
} from "../types/models";
|
||||
|
||||
// List helpers
|
||||
export function createInList(list: ArticleModel[], a: ArticleModel) {
|
||||
return [a, ...list];
|
||||
}
|
||||
|
||||
export function readInList(list: ArticleModel[], index: number) {
|
||||
if (index < 0 || index >= list.length) {
|
||||
// Soft fallback
|
||||
return undefined;
|
||||
}
|
||||
return list[index];
|
||||
}
|
||||
|
||||
export function updateInList(list: ArticleModel[], a: ArticleModel) {
|
||||
return list.map(x => (x._id === a._id ? a : x));
|
||||
}
|
||||
|
||||
export function deleteInList(list: ArticleModel[], id: string) {
|
||||
return list.filter(x => x._id !== id);
|
||||
}
|
||||
|
||||
// Map helpers
|
||||
export function createById(
|
||||
map: Record<string, ArticleModel>,
|
||||
a: ArticleModel
|
||||
) {
|
||||
if (!a._id) {
|
||||
// Soft mode: ignore create, return unchanged
|
||||
return map;
|
||||
}
|
||||
|
||||
if (map[a._id]) {
|
||||
// Soft mode: do not replace existing
|
||||
return map;
|
||||
}
|
||||
|
||||
return { ...map, [a._id]: a };
|
||||
}
|
||||
|
||||
export function readById(
|
||||
map: Record<string, ArticleModel>,
|
||||
id: string
|
||||
) {
|
||||
if (!id) return undefined;
|
||||
return map[id];
|
||||
}
|
||||
|
||||
export function updateById(
|
||||
map: Record<string, ArticleModel>,
|
||||
a: ArticleModel
|
||||
) {
|
||||
if (!a._id) {
|
||||
// Cannot update without ID
|
||||
return map;
|
||||
}
|
||||
|
||||
if (!map[a._id]) {
|
||||
// ID does not exist → soft mode: do nothing
|
||||
return map;
|
||||
}
|
||||
|
||||
return { ...map, [a._id]: a };
|
||||
}
|
||||
|
||||
export function deleteById(
|
||||
map: Record<string, ArticleModel>,
|
||||
id: string
|
||||
) {
|
||||
const { [id]: _, ...rest } = map;
|
||||
return rest;
|
||||
}
|
||||
Reference in New Issue
Block a user