import type { IRawCategoryCard, ICategoryCard } from '../../../types'; /** * Группирует категории по первой букве указанного свойства, сортируя по локали; нелитерные значения — под ключом nonLetterKey. * @param items - массив категорий * @param prop - свойство для группировки (например 'title') * @param locale - локаль для сортировки * @param nonLetterKey - ключ для нелитерных значений (по умолчанию 'POST') */ export function groupCategoriesByFirstLetter( items: Array, prop: string, locale: string, nonLetterKey = 'POST', ): Record> { const safeItems = Array.isArray(items) ? items : []; const groups = safeItems.reduce((acc, item) => { const rawValue = String(item[prop as keyof IRawCategoryCard] ?? '').trim(); const firstLetter = rawValue.normalize().at(0)?.toUpperCase() ?? ''; const key = /^\p{L}$/u.test(firstLetter) ? firstLetter : nonLetterKey; if (!acc[key]) acc[key] = []; acc[key].push({ isTop: item.is_top, title: item.title, name: item.name, videosCount: item.videosCount, guid: item.guid, icon: item.icon, }); return acc; }, {} as Record>); const collator = new Intl.Collator(locale, { sensitivity: 'base' }); return Object.fromEntries( Object.entries(groups).sort(([a], [b]) => { if (a === nonLetterKey) return 1; if (b === nonLetterKey) return -1; return collator.compare(a, b); }) ); }