All files / src/app/services/data-service name-parsing.service.ts

100% Statements 47/47
100% Branches 8/8
100% Functions 10/10
100% Lines 43/43
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 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76    1x   8x 8x 18x       1x 22x               22x 22x 22x     1x 22x 22x 1x   21x 21x     1x 22x     1x 22x 22x 21x 21x 21x   1x     1x 22x 22x 16x     6x     1x 44x 44x   44x 44x 134x 134x 134x 42x 42x 42x 42x     44x     1x  
import { IFileInfo } from '../../model/fileInfo.model';
 
export class NameParsingService {
 
  parseFiles(files: string[], prefixes: string[]): IFileInfo[] {
    return files.map(file => {
      return this.parseFile(file, prefixes);
    });
  }
 
  parseFile(file: string, prefixes: string[]): IFileInfo {
    const fileInfo = {
      name: this.parseFileName(file),
      namePrefix: '',
      baseName: this.getBaseName(file),
      displayName: '',
      effectiveDate: this.parseEffectiveDate(file),
      effectiveTime: this.parseEffectiveTime(file)
    };
    fileInfo.namePrefix = prefixes.find(pref => fileInfo.name.startsWith(pref));
    fileInfo.displayName = fileInfo.name;
    return fileInfo;
  }
 
  private getBaseName(fileName) {
    const month = this.findMonth(fileName);
    if (!month.found) {
      return fileName;
    }
    const base = fileName.substr(0, month.pos - 4).trimWithMask( '( ' );
    return base;
  }
 
  private parseFileName(fileName: string): string {
    return fileName.replace('.html', '');
  }
 
  private parseEffectiveDate(fileName: string): Date {
    const month = this.findMonth(fileName);
    if (month.found) {
      const day = parseInt(fileName.substr(month.pos - 3, 2), 0);
      const year = parseInt(fileName.substr(month.pos + 4, 4), 0);
      return new Date(year, month.number, day);
    }
    return null;
  }
 
  private parseEffectiveTime(fileName: string): string {
    const time = fileName.match(/\d\d\.\d\d/);
    if (!time) {
      return '';
    }
 
    return time[0].replace('.', ':');
  }
 
  private findMonth(fileName: string) {
    const months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
    const words = fileName.split(' ');
 
    const month = {pos: -1, number: -1, found: false};
    let monthIndex = -1;
    for (const word of words) {
      monthIndex = months.indexOf(word);
      if ( monthIndex > -1 ) {
        month.number = monthIndex;
        month.pos = fileName.indexOf(months[monthIndex]);
        month.found = true;
        break;
      }
    }
    return month;
  }
 
}