All files / src/services/cleaning CleaningService.ts

100% Statements 21/21
100% Branches 8/8
100% Functions 6/6
100% Lines 21/21
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 49 50  1x 1x     1x     9x 9x   24x 18x 18x   6x   9x     2x     7x 7x   19x 1x   18x 14x 14x   4x   7x     1x                      
import { isPlainObject } from 'lodash';
 
 
export class CleaningService {
 
  fillMissingFields(refObj: any, objects: Array<any>): Array<any> {
    return objects.map(this.fillMissingFieldsInObj.bind(this, refObj));
  }
 
  private fillMissingFieldsInObj(refObj: any, objectToFill: any): any {
    const filled: any = Object.assign({}, objectToFill);
 
    Object.keys(refObj)
      .forEach(key => {
        if (!isPlainObject(refObj[key])) {
          filled[key] = filled[key] || refObj[key];
          return;
        }
 
        filled[key] = this.fillMissingFieldsInObj(refObj[key], filled[key]);
      });
 
    return filled;
  }
 
  sortFields(refObj: any, objects: Array<any>): Array<any> {
    return objects.map(this.sortFieldsInObj.bind(this, refObj));
  }
 
  private sortFieldsInObj(refObj: any, object: any): any {
    const sorted: any = {};
 
    Object.keys(refObj)
      .forEach(key => {
        if (!object.hasOwnProperty(key)) {
          return;
        }
 
        if (!isPlainObject(refObj[key])) {
          sorted[key] = object[key];
          return;
        }
 
        sorted[key] = this.sortFieldsInObj(refObj[key], object[key]);
      });
 
    return sorted;
  }
}