2023-11-28 13:18:25 +00:00
|
|
|
import { Author, Topic } from '../graphql/schema/core.gen'
|
2023-11-14 15:10:00 +00:00
|
|
|
|
2023-10-18 10:56:41 +00:00
|
|
|
import { isAuthor } from './isAuthor'
|
2023-11-14 15:10:00 +00:00
|
|
|
import { translit } from './ru2en'
|
2023-09-18 16:33:22 +00:00
|
|
|
|
|
|
|
const prepareQuery = (searchQuery, lang) => {
|
|
|
|
const q = searchQuery.toLowerCase()
|
|
|
|
if (q.length === 0) return ''
|
|
|
|
return lang === 'ru' ? translit(q) : q
|
|
|
|
}
|
|
|
|
|
|
|
|
const stringMatches = (str, q, lang) => {
|
|
|
|
const preparedStr = lang === 'ru' ? translit(str.toLowerCase()) : str.toLowerCase()
|
|
|
|
return preparedStr.split(' ').some((word) => word.startsWith(q))
|
|
|
|
}
|
|
|
|
|
2023-10-18 10:56:41 +00:00
|
|
|
export const dummyFilter = <T extends Topic | Author>(
|
|
|
|
data: T[],
|
|
|
|
searchQuery: string,
|
2023-11-14 15:10:00 +00:00
|
|
|
lang: 'ru' | 'en',
|
2023-10-18 10:56:41 +00:00
|
|
|
): T[] => {
|
2023-09-18 16:33:22 +00:00
|
|
|
const q = prepareQuery(searchQuery, lang)
|
2023-10-18 10:56:41 +00:00
|
|
|
|
|
|
|
if (q.length === 0) {
|
|
|
|
return data
|
|
|
|
}
|
2023-09-18 16:33:22 +00:00
|
|
|
|
|
|
|
return data.filter((item) => {
|
|
|
|
const slugMatches = item.slug && item.slug.split('-').some((w) => w.startsWith(q))
|
|
|
|
if (slugMatches) return true
|
|
|
|
|
|
|
|
if ('title' in item) {
|
|
|
|
return stringMatches(item.title, q, lang)
|
|
|
|
}
|
|
|
|
|
2023-10-18 10:56:41 +00:00
|
|
|
if (isAuthor(item)) {
|
2023-09-18 16:33:22 +00:00
|
|
|
return stringMatches(item.name, q, lang) || (item.bio && stringMatches(item.bio, q, lang))
|
|
|
|
}
|
2023-10-18 10:56:41 +00:00
|
|
|
|
2023-09-18 16:33:22 +00:00
|
|
|
// 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
|
|
|
|
})
|
|
|
|
}
|