All files / lib/dynamic-form-library dynamic-form-library.service.ts

100% Statements 22/22
100% Branches 10/10
100% Functions 10/10
100% Lines 18/18

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48        1x           383x   383x 383x       1530x 556x     974x 983x 983x           983x 983x 9x 54x   2652x       2370x       383x 383x 383x      
import { Inject, Injectable } from '@angular/core';
import { DynamicFormLibrary, DynamicFormLibraryName, DYNAMIC_FORM_LIBRARY } from './dynamic-form-library';
 
@Injectable()
export class DynamicFormLibraryService {
  readonly libraryNames: DynamicFormLibraryName[];
  readonly libraryNamesReverse: DynamicFormLibraryName[];
 
  constructor(
    @Inject(DYNAMIC_FORM_LIBRARY)
    readonly library: DynamicFormLibrary,
  ) {
    this.libraryNames = this.getLibraryNames();
    this.libraryNamesReverse = [ ...this.libraryNames ].reverse();
  }
 
  filterTypes<Type extends  { type: string; libraryName: DynamicFormLibraryName }>(types: (Type | Type[])[]): Type[] {
    if (!types || !types.length) {
      return [];
    }
 
    return this.libraryNames.reduce((filteredTypes, libraryName) => {
      const libraryTypes = this.getLibraryTypes(libraryName, types, filteredTypes);
      return filteredTypes.concat(libraryTypes);
    }, []);
  }
 
  private getLibraryTypes<Type extends { type: string; libraryName: DynamicFormLibraryName }>(
    name: DynamicFormLibraryName, types: (Type | Type[])[], excludeTypes: Type[]): Type[] {
    const typesFlattened = this.getTypesFlattened(types);
    if (excludeTypes && excludeTypes.length) {
      const excludeTypeNames = excludeTypes.map(type => type.type);
      return typesFlattened.filter(type => type.libraryName === name && !excludeTypeNames.includes(type.type));
    }
    return typesFlattened.filter(type => type.libraryName === name);
  }
 
  private getTypesFlattened<Type>(types: (Type | Type[])[]): Type[] {
    return types.reduce<Type[]>((result, type) => result.concat(type), []);
  }
 
  private getLibraryNames(): DynamicFormLibraryName[] {
    const referenceLibraryNames = this.library.references || [];
    const referenceLibraryNamesReverse = [ ...referenceLibraryNames ].reverse();
    return [ this.library.name, ...referenceLibraryNamesReverse ];
  }
}