All files / src/app/shared/services time-diff.service.ts

97.22% Statements 35/36
90% Branches 9/10
100% Functions 9/9
96.88% Lines 31/32

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 49 50 51 527x   7x         7x     7x 5x 5x 5x 5x     5x     7x 10x 10x 10x 10x   30x 30x     7x 65x 65x 2x   63x 63x     7x 69x 69x 69x 69x     7x 207x 207x   7x  
import { Injectable } from '@angular/core';
 
import * as _ from 'lodash';
 
@Injectable({
  providedIn: 'root'
})
export class TimeDiffService {
  constructor() {}
 
  calculateDuration(startDate: Date, endDate: Date): string {
    const startTime = +startDate;
    const endTime = +endDate;
    const duration = this.getDuration(Math.abs(startTime - endTime));
    Iif (startTime > endTime) {
      return '-' + duration;
    }
    return duration;
  }
 
  private getDuration(ms: number): string {
    const date = new Date(ms);
    const h = date.getUTCHours();
    const m = date.getUTCMinutes();
    const d = Math.floor(ms / (24 * 3600 * 1000));
 
    const format = (n, s) => (n ? n + s : n);
    return [format(d, 'd'), format(h, 'h'), format(m, 'm')].filter((x) => x).join(' ');
  }
 
  calculateDate(date: Date, duration: string, reverse?: boolean): Date {
    const time = +date;
    if (_.isNaN(time)) {
      return;
    }
    const diff = this.getDurationMs(duration) * (reverse ? -1 : 1);
    return new Date(time + diff);
  }
 
  private getDurationMs(duration: string): number {
    const d = this.getNumbersFromString(duration, 'd');
    const h = this.getNumbersFromString(duration, 'h');
    const m = this.getNumbersFromString(duration, 'm');
    return ((d * 24 + h) * 60 + m) * 60000;
  }
 
  private getNumbersFromString(duration, prefix): number {
    const match = duration.match(new RegExp(`[0-9 ]+${prefix}`, 'i'));
    return match ? parseInt(match, 10) : 0;
  }
}