This repository was archived by the owner on Jun 27, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 41
This repository was archived by the owner on Jun 27, 2023. It is now read-only.
Use generic Types! #74
Copy link
Copy link
Open
Description
Can you use generic types instead converting the whole data object to type any. Otherwise all TypeScript information about the object properties will be lost!
Here is my implementation:
/**
* Search Filter Pipe
* @param items object from array
* @param term term's search
* @param excludes array of strings which will ignored during search
*/
public transform<T>(items: T[], term: string, excludes: any[] = []): T[] {
if (!term || !items) return items;
return SearchFilterPipe.filter(items, term, excludes);
}
/**
* Filer items[]
* @param items List of items to filter
* @param term a string term to compare with every property of the list
* @param excludes List of keys which will be ignored during search
*/
private static filter<T>(items: T[], term: string, excludes: any[]): T[] {
const toCompare = term.toLowerCase();
/**
* Check filterable object props
*/
function checkInside(item: any, term: string): boolean {
if (typeof item === 'string' && item.toString().toLowerCase().includes(toCompare)) {
return true;
}
for (let property in item) {
if (item[property] === null || item[property] == undefined || excludes.includes(property)) {
continue;
}
if (typeof item[property] === 'object') {
if (checkInside(item[property], term)) {
return true;
}
} else if (item[property].toString().toLowerCase().includes(toCompare)) {
return true;
}
}
return false;
}
return items.filter(function (item) {
return checkInside(item, term);
});
}Metadata
Metadata
Assignees
Labels
No labels