Skip to content
This repository was archived by the owner on Jun 27, 2023. It is now read-only.
This repository was archived by the owner on Jun 27, 2023. It is now read-only.

Use generic Types! #74

@jonaaix

Description

@jonaaix

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

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions