initial commit
This commit is contained in:
37
frontend/src/utils.ts
Normal file
37
frontend/src/utils.ts
Normal file
@@ -0,0 +1,37 @@
|
||||
import { Model } from './types';
|
||||
|
||||
export const parseFilter = (filterStr: string) => {
|
||||
const colonIndex = (filterStr || '').indexOf(':');
|
||||
if (colonIndex === -1) return null;
|
||||
|
||||
const path = filterStr.slice(0, colonIndex).trim().replace(/^\./, '');
|
||||
const value = filterStr
|
||||
.slice(colonIndex + 1)
|
||||
.trim()
|
||||
.replace(/^["']|["']$/g, '');
|
||||
|
||||
return { path, value };
|
||||
};
|
||||
|
||||
export const matchesFilter = <T>(
|
||||
obj: T,
|
||||
path: string,
|
||||
value: string,
|
||||
): boolean => {
|
||||
const fieldValue = path
|
||||
.split('.')
|
||||
.reduce<unknown>(
|
||||
(o, key) => (o as Record<string, unknown>)?.[key],
|
||||
obj as Record<string, unknown>,
|
||||
);
|
||||
return Array.isArray(fieldValue)
|
||||
? fieldValue.includes(value)
|
||||
: fieldValue === value;
|
||||
};
|
||||
|
||||
export const applyFilter = (data: Model[], filterStr: string) => {
|
||||
const filter = parseFilter(filterStr);
|
||||
return filter
|
||||
? data.filter((item) => matchesFilter(item, filter.path, filter.value))
|
||||
: data;
|
||||
};
|
||||
Reference in New Issue
Block a user