diff options
Diffstat (limited to 'src/lib/shared/group-by-category.ts')
| -rw-r--r-- | src/lib/shared/group-by-category.ts | 23 |
1 files changed, 23 insertions, 0 deletions
diff --git a/src/lib/shared/group-by-category.ts b/src/lib/shared/group-by-category.ts new file mode 100644 index 0000000..e9b0acd --- /dev/null +++ b/src/lib/shared/group-by-category.ts @@ -0,0 +1,23 @@ +export function groupByCategory< + TItem extends { categoryName: string | null }, + TCategory extends { name: string }, +>(items: TItem[], categories: TCategory[]): [string, TItem[]][] { + const groups = new Map<string, TItem[]>(); + for (const item of items) { + const key = item.categoryName ?? 'Non catégorisé'; + const list = groups.get(key); + if (list) list.push(item); + else groups.set(key, [item]); + } + + const result: [string, TItem[]][] = []; + for (const cat of categories) { + const list = groups.get(cat.name); + if (list?.length) result.push([cat.name, list]); + } + const uncategorized = groups.get('Non catégorisé'); + if (uncategorized?.length) { + result.unshift(['Non catégorisé', uncategorized]); + } + return result; +} |
