JSFiddle - React, Tailwind, and code Playground
by artgas_pro
TypeScript
/*===========СОРТИРОВКИ=============*/
const exclude = (data: User[], filters: Filter): User[] => {
if(filters.length === 0) return data
return data.filter(item => {
return filters.some(conditionGroup => {
return conditionGroup.every(condition => {
return String(item[condition.key]).toLowerCase() !== String(condition.value).toLowerCase();
});
});
});
}
const include = (data: User[], filters: Filter): User[] => {
if(filters.length === 0) return data
return data.filter(item => {
return filters.some(conditionGroup => {
return conditionGroup.every(condition => {
return String(item[condition.key]).toLowerCase() === String(condition.value).toLowerCase();
});
});
});
}
const sort = (data: User[], filters: CustomFilter): User[] => {
if(filters.length === 0) return data
return data.sort((a,b)=> {
for(const filter of filters){
const {key, value} = filter;
if (value === 'ASC') {
if (a[key] < b[key]) return -1;
if (a[key] > b[key]) return 1;
} else if (value === 'DESC') {
if (a[key] > b[key]) return -1;
if (a[key] < b[key]) return 1;
}
}
return 0;
});
}
const settings: ['ASC', 'DESC'] = ['ASC', 'DESC'];
sort.settings = settings;
type ModuleSortSelectCustomValue = typeof settings
/*===========СОРТИРОВКИ=============*/
/*===========ОСНОВНЫЕТИПЫ=============*/
type User = {
name: string;
rating: number;
disabled: boolean;
email: string;
}
type FilterCondition = {
key: keyof User;
value: User[keyof User];
}[];
type Filter = FilterCondition[];
type CustomSelectValues = ModuleSortSelectCustomValue | [];
type CustomFilter = {
key: keyof User;
value: CustomSelectValues[number]
}[];
type SortFunction = (data: User[], filters: Filter) => User[];
type CustomSortFunction = {
(data: User[], filters: CustomFilter): User[],
settings: CustomSelectValues
};
type Sorts = {
include: SortFunction;
exclude:...