webapp/src/intl/dummyFilter.ts

43 lines
1.2 KiB
TypeScript
Raw Normal View History

import type { Author, Topic } from '~/graphql/schema/core.gen'
2024-08-30 13:45:17 +00:00
import { translit } from './translit'
2024-02-04 09:03:15 +00:00
const prepareQuery = (searchQuery: string, lang: string) => {
const q = searchQuery.toLowerCase()
if (q.length === 0) return ''
return lang === 'ru' ? translit(q) : q
}
2024-02-04 09:03:15 +00:00
const stringMatches = (str: string, q: string, lang: string) => {
const preparedStr = lang === 'ru' ? translit(str.toLowerCase()) : str.toLowerCase()
return preparedStr.split(' ').some((word) => word.startsWith(q))
}
export const dummyFilter = <T extends Topic | Author>(
data: T[],
searchQuery: string,
2024-06-26 08:22:05 +00:00
lang: 'ru' | 'en'
): T[] => {
const q = prepareQuery(searchQuery, lang)
if (q.length === 0) {
return data
}
return data.filter((item) => {
2024-02-04 09:03:15 +00:00
const slugMatches = item.slug?.split('-').some((w) => w.startsWith(q))
if (slugMatches) return true
if ('title' in item) {
2024-06-24 17:50:27 +00:00
return stringMatches(item?.title || '', q, lang)
}
2024-07-05 14:08:12 +00:00
if ('name' in item) {
2024-06-24 17:50:27 +00:00
return stringMatches(item?.name || '', q, lang) || (item.bio && stringMatches(item.bio, q, lang))
}
// If it does not match any of the 'slug', 'title', 'name' , 'bio' fields
// current element should not be included in the filtered array
return false
})
}