Line data Source code
1 : import { deburr } from 'es-toolkit'
2 :
3 : export type TableSortDirection = 'ascending' | 'descending'
4 :
5 46 : const collator = new Intl.Collator(undefined, { numeric: true })
6 :
7 14242 : function normalizeSearchText(text: string) {
8 14242 : return deburr(text).toLocaleLowerCase()
9 : }
10 :
11 98 : export function filterByQuery<T>(
12 : items: readonly T[],
13 : query: string,
14 : getSearchFields: (item: T) => string[]
15 : ): T[] {
16 98 : const normalizedQuery = normalizeSearchText(query.trim())
17 98 : return items.filter((item) =>
18 : getSearchFields(item).some((field) =>
19 : normalizeSearchText(field).includes(normalizedQuery)
20 : )
21 : )
22 : }
23 :
24 98 : export function sortByText<T>(
25 : items: readonly T[],
26 : direction: TableSortDirection | null,
27 : getText: (item: T) => string
28 : ): T[] {
29 98 : if (!direction) return [...items]
30 0 : return [...items].sort((a, b) => {
31 0 : const result = collator.compare(getText(a), getText(b))
32 0 : return direction === 'ascending' ? result : -result
33 : })
34 : }
|