38 lines
955 B
TypeScript
38 lines
955 B
TypeScript
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;
|
|
};
|