utils.tsx 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. export type Filters<T> = {
  2. [key: string]: (item: T) => boolean;
  3. };
  4. export const getFilteredItems = <T,>({
  5. filters,
  6. items,
  7. searchTerm,
  8. searchProp,
  9. }: {
  10. filters: Filters<T>;
  11. items: T[];
  12. searchProp: keyof T;
  13. searchTerm: string;
  14. }) => {
  15. if (!searchTerm && Object.keys(filters).length === 0) {
  16. return items;
  17. }
  18. const normalizedSearchTerm = searchTerm.toLowerCase();
  19. return items.filter(item => {
  20. let doesMatch = false;
  21. const searchValue = item[searchProp];
  22. if (typeof searchValue === 'string') {
  23. doesMatch = searchValue.toLowerCase().includes(normalizedSearchTerm);
  24. } else {
  25. // As this is a generic typed value, we can't know for sure its value type. So we use JSON.stringify to make sure we get a string.
  26. doesMatch = JSON.stringify(searchValue)
  27. .toLowerCase()
  28. .includes(normalizedSearchTerm);
  29. }
  30. for (const key in filters) {
  31. if (filters.hasOwnProperty(key)) {
  32. const filter = filters[key];
  33. if (!filter(item)) {
  34. return false;
  35. }
  36. }
  37. }
  38. return doesMatch;
  39. });
  40. };